添加更多细节:有问题的类型,如 NSJSONReadingOptions,在 Obj-C 中声明为 NS_OPTIONS。
在 Swift 2 之前
在 Swift 2 之前,这些是作为 RawOptionSetType 导入到 Swift 中的,这需要 BitwiseOperationsType 和 NilLiteralConvertible。这允许您传递nil,并将值与运算符a | b、a & ~b 等结合起来。
/// Protocol for `NS_OPTIONS` imported from Objective-C
protocol RawOptionSetType : BitwiseOperationsType, NilLiteralConvertible { ...
protocol BitwiseOperationsType {
func &(lhs: Self, rhs: Self) -> Self
func |(lhs: Self, rhs: Self) -> Self
func ^(lhs: Self, rhs: Self) -> Self
prefix func ~(x: Self) -> Self
static var allZeros: Self { get }
}
现在
在 Swift 2 中,它得到了更多的概括。这些现在是 OptionSetType,需要 SetAlgebraType 和 RawRepresentable。 (底层 RawValue 类型可能是也可能不是 BitwiseOperationsType。)
public protocol OptionSetType : SetAlgebraType, RawRepresentable {
typealias Element = Self
public init(rawValue: Self.RawValue)
}
public protocol SetAlgebraType : Equatable, ArrayLiteralConvertible {
typealias Element
public init()
public func contains(member: Self.Element) -> Bool
public func union(other: Self) -> Self
public func intersect(other: Self) -> Self
public func exclusiveOr(other: Self) -> Self
// and more...
}
SetAlgebraType 不再是 NilLiteralConvertible,而是 ArrayLiteralConvertible,因此您可以使用 [] 而不是 nil 来表示“没有选项”。
您可以在一个数组中组合多个选项:options: [.MutableLeaves, .AllowFragments]。
SetAlgebraType 的函数名称也比那些按位运算符&、|、^ 等更具可读性:
public func contains(member: Self.Element) -> Bool
public func union(other: Self) -> Self
public func intersect(other: Self) -> Self
public func exclusiveOr(other: Self) -> Self
所以你可以使用if jsonOptions.contains(.AllowFragments) { ...等。