![](/img/trans.png)
[英]How can I find if the index number for a specific item in an array also exists as an integer in the same array?
[英]How can I find an item of a specific type in an array
如何在數組中找到特定類型的項目?
例如:我有一系列寵物。
let pets: [Animal] = [Cat(), Cat(), Fish(), Dog()]
如何找到 Dog 類型的第一項?
在 Swift 中非常簡單, first(where
方法。像這樣:
let cat = pets.first { $0 is Cat }
或者,擴展版本:
let cat = pets.first { (animal) -> Bool in
return animal is Cat
}
第一段和第二段代碼做同樣的事情。
更通用的版本,function 看起來像這樣:
func findAnimal<T: Animal>(ofType: T.Type) -> Animal? {
return pets.first {
guard let t = $0 as? T else {
return false
}
return type(of: t) == ofType
}
}
例如:
findAnimal(ofType: Dog.self)
將從數組中返回一只狗
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.