I have this enum:
enum Animal {
case cat(CatModel)
case dog(DogModel)
}
还有一组动物:
var animals: [Animal]
我需要通过 Dog 没有的属性,例如 litterBoxId,在此数组中查找 Cat 对象。
let cat = animals.first(where: {$0.litterBoxId == 7})
这当然是一个错误:
Value of type 'MyViewController.Animal' has no member 'litterBoxId'
我该如何实现这个?我也尝试过。
($0 as CatModel).litterBoxId
func litterboxID(of: Animal, matches: Int) -> Bool
,并将你的模式匹配逻辑放在那里,这样你就可以只调用animals.first(where: { litterboxID(of: Animal, matches: 7) }
。更好的做法是,像我在答案中提到的那样(以及它的注释),把访问这些字段的权限放在枚举本身中。更好的方法是使用一个协议,它可以包含这些字段(如果适用)并允许您轻松地进行强制转换以获取其他内容。 - Alexander