Swift - 在枚举数组中查找具有关联值的对象

sol*_*eil 6 arrays search enums swift associated-value

我有这个枚举:

enum Animal {       
    case cat(CatModel)
    case dog(DogModel)
}
Run Code Online (Sandbox Code Playgroud)

还有一系列动物:

var animals: [Animal]
Run Code Online (Sandbox Code Playgroud)

我需要通过 Dog 没有的属性在该数组中找到 Cat 对象。litterBoxId例如。

let cat = animals.first(where: {$0.litterBoxId == 7})
Run Code Online (Sandbox Code Playgroud)

这当然有一个错误:

Value of type 'MyViewController.Animal' has no member 'litterBoxId'
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我也尝试过

($0 as CatModel).litterBoxId
Run Code Online (Sandbox Code Playgroud)

gch*_*ita 8

您可以使用模式匹配通过两种方式来完成此任务。

使用开关:

let cat = animals.first(where: {
    switch $0 {
    case .cat(let catModel) where catModel.litterBoxId == 7:
        return true
    default:
        return false
    }
})
Run Code Online (Sandbox Code Playgroud)

或者如果:

let cat = animals.first(where: {
    if case .cat(let catModel) = $0, catModel.litterBoxId == 7 {
        return true
    }
    return false
})
Run Code Online (Sandbox Code Playgroud)

更新:正如@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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你的代码就会干净得多:

let cat = animals.first(where: { $0.matches(litterboxID: 7) })
Run Code Online (Sandbox Code Playgroud)