【问题标题】:Swift 2.0 - `nil` or `0` enum argumentsSwift 2.0 - `nil` 或 `0` 枚举参数
【发布时间】:2015-08-23 17:44:58
【问题描述】:

我在 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)

【问题讨论】:

标签: swift enums swift2


【解决方案1】:

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

【讨论】:

  • 那很快,谢谢!我会尽快接受你的回答:)
【解决方案2】:

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

在 Swift 2 之前

在 Swift 2 之前,这些是作为 RawOptionSetType 导入到 Swift 中的,这需要 BitwiseOperationsType 和 NilLiteralConvertible。这允许您传递nil,并将值与运算符a | ba & ~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) { ...等。

【讨论】:

    【解决方案3】:

    你通过[](一个空集)

    一些enums 有一个明确的选项,表示0,但Swift 3 有时不导入这些,因为[] 表示相同的意思。喜欢UIViewAutoresizingUIViewAutoresizingNone

    【讨论】:

    • 这个答案和接受的有什么区别?
    • 更多的是描述(更深入)。即我想知道为什么有时我们都有。如果您是来寻求解决方案并且不关心上下文,那么接受 A 就可以了。
    猜你喜欢
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多