gpt4 book ai didi

ios - 在数组中查找枚举类型

转载 作者:可可西里 更新时间:2023-11-01 00:33:59 25 4
gpt4 key购买 nike

如果我有这个枚举:

enum TestEnum {
case typeA
case typeB(Int)
}

和这个数组:let 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)

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

关于ios - 在数组中查找枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47392436/

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