Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Enums 如果有关联的值,则枚举值测试失败?_Enums_Swift - Fatal编程技术网

Enums 如果有关联的值,则枚举值测试失败?

Enums 如果有关联的值,则枚举值测试失败?,enums,swift,Enums,Swift,我正在操场上测试,我不知道怎么做。对于没有关联值的普通枚举,一切正常 enum CompassPoint { case North case South case East case West } var direction = CompassPoint.East if direction != .West { println("Go West!") } 但是,如果我的某个枚举具有关联值,则方向测试将失败,并出现以下错误:找不到成员“West” en

我正在操场上测试,我不知道怎么做。对于没有关联值的普通枚举,一切正常

enum CompassPoint {
    case North
    case South
    case East
    case West
}

var direction = CompassPoint.East

if direction != .West {
    println("Go West!")
}
但是,如果我的某个枚举具有关联值,则方向测试将失败,并出现以下错误:找不到成员“West”

enum CompassPoint {
    case North(Int)
    case South
    case East
    case West
}

var direction = CompassPoint.East

if direction != .West {
    println("Go West!")
}

我可以做些什么来允许此测试?

当枚举的原始值为
可等式时,它们会自动
可等式化。在第一种情况下,假定原始值为
Int
,但如果您给它另一种特定类型,如
UInt32
,甚至
String
,则该值可以工作

但是,一旦添加了关联值,这种与
equalable
的自动一致性就不再发生,因为您可以声明:

let littleNorth = CompassPoint.North(2)
let bigNorth = CompassPoint.North(99999)
这些是平等的吗?斯威夫特怎么知道?您必须声明
enum
Equatable
,然后实现
=
操作符来告诉它:

enum CompassPoint : Equatable {
    case North(Int)
    case South
    case East
    case West
}

public func ==(lhs:CompassPoint, rhs:CompassPoint) -> Bool {
    switch (lhs, rhs) {
    case (.North(let lhsNum), .North(let rhsNum)):
        return lhsNum == rhsNum
    case (.South, .South): return true
    case (.East, .East): return true
    case (.West, .West): return true
    default: return false
    }
}
现在您可以测试相等或不相等,如下所示:

let otherNorth = CompassPoint.North(2)
println(littleNorth == bigNorth)            // false
println(littleNorth == otherNorth)          // true
返回true的案例可以组合为单个案例:
case(.South,.South),(.East,.East),(.West,.West):从Swift 4.1返回true
,因为,Swift还支持为具有关联值的枚举合成
equalable
Hashable