gpt4 book ai didi

enums - 如果一个具有关联值,则对枚举值的测试会失败?

转载 作者:IT王子 更新时间:2023-10-29 05:25:54 25 4
gpt4 key购买 nike

我正在 Playground 中对此进行测试,但我不确定如何执行此操作。使用没有关联值的普通枚举,一切都很好。

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!")
}

我该怎么做才能进行此测试?

最佳答案

当枚举具有 Equatable 的原始值时,它们自动成为 Equatable。在你的第一种情况下,原始值被假定为 Int,但如果你给它另一种特定类型,如 UInt32 甚至 String<,它就会起作用.

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

let littleNorth = CompassPoint.North(2)
let bigNorth = CompassPoint.North(99999)

它们相等吗? swift 怎么知道?您必须通过将 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

关于enums - 如果一个具有关联值,则对枚举值的测试会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25726493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com