Swift 2.0 - `nil`或`0`枚举参数

kee*_*n3d 8 enums swift swift2

我在Swift 2.0中的几个函数中遇到了这个问题,并想知道是否有解决方法.现在似乎无法在Swift 2.0中指定枚举参数.例如,这两种方法似乎需要除了nil0传入之外的东西.有没有办法解决这个问题?

// Cannot invoke '...' with argument list of type ... options: Int
NSCalendar.currentCalendar().dateByAddingComponents(components, fromDate: self.date, options: 0)
NSJSONSerialization.JSONObjectWithData(data, options: 0)

// Cannot invoke '...' with argument list of type ... options: nil
NSCalendar.currentCalendar().dateByAddingComponents(components, fromDate: self.date, options: nil)
NSJSONSerialization.JSONObjectWithData(data, options: nil)
Run Code Online (Sandbox Code Playgroud)

Aar*_*ger 13

选项现在被指定为一个集合,所以只需传递一个空集:options: [].


jtb*_*des 9

只是添加更多细节:有问题的类型,如NSJSONReadingOptions,NS_OPTIONS在Obj-C 中声明.

在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 }
}
Run Code Online (Sandbox Code Playgroud)

如今

在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...
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

所以你可以使用if jsonOptions.contains(.AllowFragments) { ...等等.