强劲的EnumerationsSwift中的枚举比Objective-C中的有很大提高。 修复 EnumsApple一直提倡显示的提供枚举类型的大小,不过被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 } 拓展EnumsEnums 在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对此的看法。 |