Ios 在数组中查找枚举类型
如果我有此枚举:Ios 在数组中查找枚举类型,ios,swift,enums,Ios,Swift,Enums,如果我有此枚举: enum TestEnum { case typeA case typeB(Int) } 这个数组:让testArray=[TestEnum.typeB(1),.typeA,.typeB(3)] 是否有一种比以下方法更简单的方法来确定该数组中是否包含项: if testArray.contains(where: {if case .typeA = $0 { return true }; return false}) { print("contained
enum TestEnum {
case typeA
case typeB(Int)
}
这个数组:让testArray=[TestEnum.typeB(1),.typeA,.typeB(3)]
是否有一种比以下方法更简单的方法来确定该数组中是否包含项:
if testArray.contains(where: {if case .typeA = $0 { return true }; return false}) {
print("contained")
} else {
print("not found")
}
不太可能,但您可以在枚举上定义一个帮助器,使其在调用站点上的粗糙度降低一点
enum TestEnum {
case typeA
case typeB(Int)
var isTypeA: Bool {
switch self {
case .typeA:
return true
case .typeB:
return false
}
}
}
let filtered: [TestEnum] = [.typeB(1), .typeA, .typeB(3)].filter { $0.isTypeA }
要使其更具可读性,可以向枚举中添加如下函数:
enum TestEnum {
case typeA
case typeB(Int)
static func ==(a: TestEnum, b: TestEnum) -> Bool {
switch (a, b) {
case (typeB(let a), .typeB(let b)) where a == b: return true
case (.typeA, .typeA): return true
default: return false
}
}
}
let testArray = [TestEnum.typeB(1), .typeA, .typeB(3)]
if testArray.contains(where: { $0 == .typeA }) {
print("contained")
} else {
print("not found")
}
如果你使你的枚举相等,你可以这样做
enum TestEnum: Equatable {
case testA
case testB(Int)
static func ==(lhs: TestEnum, rhs: TestEnum) -> Bool {
switch (lhs, rhs) {
case (.testA, .testA):
return true
case (.testB(let a), .testB(let b)):
return a == b
default:
return false
}
}
}
let array: [TestEnum] = [.testA, .testB(1)]
array.contains(.testA) // true
array.contains(.testB(1)) // true
array.contains(.testB(3)) // false
这意味着您可以使用更简单的contains函数形式,而不必使用块