// In Swift, the UITableViewCellStyle enumeration is imported like this: public enum UITableViewCellStyle : Int { case `default` = 0 case value1 = 1 case value2 = 2 case subtitle = 3 }
NS_CLOSED_ENUM
用于不会变更枚举成员的简单的枚举(简称 “冻结枚举” )。对应 Swift 中的 @frozen 关键字。
相比较于非冻结枚举,冻结枚举降低了灵活性,但提升了性能。一旦枚举被标记为冻结枚举,那么在未来版本的库中就不能通过添加、删除或重新排序枚举的 case,否则会破坏 ABI 兼容性
// In Swift, the NSComparisonResult enumeration is imported like this: @frozen public enum NSComparisonResult : Int { case orderedAscending = -1 case orderedSame = 0 case orderedDescending = 1 }
// In Swift, the UIViewAutoresizing type is imported like this: public struct UIViewAutoresizing: OptionSet { public init(rawValue: UInt)
public static var flexibleLeftMargin: UIViewAutoresizing { get } public static var flexibleWidth: UIViewAutoresizing { get } public static var flexibleRightMargin: UIViewAutoresizing { get } public static var flexibleTopMargin: UIViewAutoresizing { get } public static var flexibleHeight: UIViewAutoresizing { get } public static var flexibleBottomMargin: UIViewAutoresizing { get } }
NS_TYPED_ENUM
用于类型常量枚举
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Store the three traffic light color options as 0, 1, and 2. typedef long TrafficLightColor NS_TYPED_ENUM;
// In Swift, the TrafficLightColor type is imported like this: public struct TrafficLightColor : Hashable, Equatable, RawRepresentable { public init(rawValue: Int) } extension TrafficLightColor { public static let red: TrafficLightColor public static let yellow: TrafficLightColor public static let green: TrafficLightColor }
// Objective-C 的常数被自动转换成 Swift Struct public struct DCDictionaryKey : Hashable, Equatable, RawRepresentable { public init(rawValue: String) } extension DCDictionaryKey { public static let title : DCDictionaryKey public static let subtitle : DCDictionaryKey public static let count : DCDictionaryKey }
NS_TYPED_EXTENSIBLE_ENUM
用于可扩展的类型常量枚举
1 2 3 4 5 6 7 8 9 10 11 12
// declared typedef long FavoriteColor NS_TYPED_EXTENSIBLE_ENUM; FOUNDATION_EXTERN FavoriteColor const FavoriteColorBlue;
// imported public struct FavoriteColor : Hashable, Equatable, RawRepresentable { public init(_ rawValue: Int) public init(rawValue: Int) } extension FavoriteColor { public static let blue: FavoriteColor }
小结
使用 NS_ENUM 和 NS_OPTIONS 来声明简单枚举和选项枚举,以优化 Swift 编程体验。
NS_CLOSED_ENUM 用于声明不会变更枚举成员的冻结枚举,对应 Swift 中的 @frozen 关键字,以降低灵活性的代价,换取了性能上的提升。
NS_STRING_ENUM/NS_EXTENSIBLE_STRING_ENUM、NS_TYPED_ENUM/NS_TYPED_EXTENSIBLE_ENUM 用于声明字符串常量/类型常量枚举,这在混编时在 Swift 中使用起来更简洁优雅更符合 Swift 的使用习惯。