设为首页收藏本站

LUPA开源社区

 找回密码
 注册
文章 帖子 博客
LUPA开源社区 首页 业界资讯 技术文摘 查看内容

从Objective-C到Swift—Swift糖果

2014-6-30 14:50| 发布者: joejoe0332| 查看: 5874| 评论: 0|原作者: GoodLoser, chasehong|来自: oschina

摘要: Swift带来很多确实很棒的特性,使得很难再回到Objective-C。主要的特性是安全性,不过这也被看成是一种额外副作用。


强劲的Enumerations

  Swift中的枚举比Objective-C中的有很大提高。


修复 Enums

  Apple一直提倡显示的提供枚举类型的大小,不过被Objective-C搞乱了:

// Apple recommended enum definition in Objective-C
typedef NS_ENUM(NSInteger, UIViewAnimationCurve) {
    UIViewAnimationCurveEaseInOut,
    UIViewAnimationCurveEaseIn,
    UIViewAnimationCurveEaseOut,
    UIViewAnimationCurveLinear
};

// Previous Apple recommended enum definition in Objective-C. No link between 
// enum values and theUIViewAnimationCurve type.
typedef enum {
    UIViewAnimationCurveEaseInOut,
    UIViewAnimationCurveEaseIn,
    UIViewAnimationCurveEaseOut,
    UIViewAnimationCurveLinear
};
typedef NSInteger UIViewAnimationCurve;

// Traditional enum definition in Objective-C. No explicit fixed size.
typedef enum {
    UIViewAnimationCurveEaseInOut,
    UIViewAnimationCurveEaseIn,
    UIViewAnimationCurveEaseOut,
    UIViewAnimationCurveLinear
} UIViewAnimationCurve;

Swift中的修复:

enum UIViewAnimationCurve : Int {
    case EaseInOut
    case EaseIn
    case EaseOut
    case Linear
}


拓展Enums

  Enums 在Swift中更进一步,只作为一个独立的选项列表。你可以添加方法(以及计算属性):

enum UIViewAnimationCurve : Int {
    case EaseInOut
    case EaseIn
    case EaseOut
    case Linear
    func typeName() -> String {
        return "UIViewAnimationCurve"
    }
}


  使用类型拓展,你可以向枚举中添加任何你想要的方法:

extension UIViewAnimationCurve {
    func description() -> String {
        switch self {
        case EaseInOut:
            return "EaseInOut"
        case EaseIn:
            return "EaseIn"
        case EaseOut:
            return "EaseOut"
        case Linear:
            return "Linear"
        }
    }
}


向Enums中添加值

  Swift中的枚举跟进一步,允许每一个独立的选项都有一个对应的值:

enum Shape {
    case Dot
    case Circle(radius: Double) // Require argument name!
    case Square(Double)
    case Rectangle(width: Double, height: Double) // Require argument names!
    func area() -> Double {
        switch self {
        case Dot:
            return 0
        case Circle(let r): // Assign the associated value to the constant 'r'
            return π*r*r
        case Square(let l):
            return l*l
        case Rectangle(let w, let h):
            return w*h
        }
    }
}
var shape = Shape.Dot
shape = .Square(2)
shape = .Rectangle(width: 3, height: 4) // Argument names required
shape.area()

  如果你喜欢,你可以把它当做一个安全的union类型。或者只用枚举应该做的事情。


  Enumerations 文章介绍了更多关于Apple对此的看法。



酷毙

雷人

鲜花

鸡蛋

漂亮
  • 快毕业了,没工作经验,
    找份工作好难啊?
    赶紧去人才芯片公司磨练吧!!

最新评论

关于LUPA|人才芯片工程|人才招聘|LUPA认证|LUPA教育|LUPA开源社区 ( 浙B2-20090187 浙公网安备 33010602006705号   

返回顶部