switch 是匹配一系列案例的常用模式。见The Swift Programming Language: Enumerations: Matching Enumeration Values with a Switch Statement。
例如。:
switch itemStatus {
case .locked, .hasHistoryLocked:
print("YES")
default:
print("NO")
}
如果您想在if 或guard 语句中添加它,您可以将以上内容包装在计算属性中。例如。,
extension ItemStatus {
var isLocked: Bool {
switch self {
case .locked, .hasHistoryLocked:
return true
default:
return false
}
}
}
然后您可以执行以下操作:
func doSomethingIfUnlocked() {
guard !itemStatus.isLocked else {
return
}
// proceed with whatever you wanted if it was unlocked
}
或者,您可以为此类型添加Equatable 一致性。所以,想象ItemStatus 是这样定义的:
enum ItemStatus {
case locked
case hasHistoryLocked
case unlocked(Int)
}
现在,如果这是您的类型,您可以添加 Equatable 一致性:
enum ItemStatus: Equatable {
case locked
case hasHistoryLocked
case unlocked(Int)
}
如果它不是您的类型并且您不能简单地编辑原始声明,您可以添加Equatable 一致性:
extension ItemStatus: Equatable {
static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (.locked, .locked), (.hasHistoryLocked, .hasHistoryLocked): // obviously, add all cases without associated values here
return true
case (.unlocked(let lhsValue), .unlocked(let rhsValue)) where lhsValue == rhsValue: // again, add similar patterns for all cases with associated values
return true
default:
return false
}
}
}
但是,您将Equatable 一致性添加到ItemStatus,然后您可以执行以下操作:
func doSomethingIfUnlocked() {
guard itemStatus != .locked, itemStatus != .hasHistoryLocked else {
return
}
// proceed with whatever you wanted if it was unlocked
}