我有这个枚举:
enum Animal {
case cat(CatModel)
case dog(DogModel)
}
还有一系列动物:var animals: [Animal]
我需要通过 Dog 没有的属性在这个数组中找到一个 Cat 对象。 litterBoxId
例如。let cat = animals.first(where: {$0.litterBoxId == 7})
这当然有一个错误:Value of type 'MyViewController.Animal' has no member 'litterBoxId'
我怎样才能做到这一点?我也试过($0 as CatModel).litterBoxId
最佳答案
您可以使用模式匹配通过 2 种方式完成此操作。
使用开关:
let cat = animals.first(where: {
switch $0 {
case .cat(let catModel) where catModel.litterBoxId == 7:
return true
default:
return false
}
})
或者如果:let cat = animals.first(where: {
if case .cat(let catModel) = $0, catModel.litterBoxId == 7 {
return true
}
return false
})
更新 :正如@Alexander-ReinstateMonica 在他的 commnet 中提到的,将这个逻辑隐藏在这样的函数后面会更合适:extension Animal {
func matches(litterboxID: Int) -> Bool {
switch self {
case .cat(let catModel) where catModel.litterBoxId == 7:
return true
default:
return false
}
}
}
然后你的代码会更干净:let cat = animals.first(where: { $0.matches(litterboxID: 7) })
关于arrays - Swift - 在具有关联值的枚举数组中查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63513996/