[英]How to make a constrained extension of Collection generic in Swift?
語境
我有一個符合協議Entity
的類Profile
。 我還向所有 Element 是Profile
的Swift Collections
添加了一個搜索方法。
但是,我想讓這個泛型不僅支持Profile
,而且支持符合Entity
的每個對象。
代碼
protocol Entity {
var name: String { get }
}
class Profile: Entity { ... }
extension Collection where Element == Profile {
func searched(with search: String) -> [Profile] {
guard !(search.isEmpty) else { return self }
return self.filter { ($0.name.lowercased().contains(search.lowercased())) }
}
}
題
如何使搜索方法通用以支持符合Entity
的所有對象?
首先,您應該將擴展名更改為以下代碼
extension Collection where Iterator.Element: Entity
接下來,將方法的返回類型更改為
func searched(with search: String) -> [Iterator.Element]
最后,擴展可以是這樣的:
extension Collection where Iterator.Element: Entity {
func searched(with search: String) -> [Iterator.Element] {
guard !(search.isEmpty) else { return [Iterator.Element]() }
return self.filter { ($0.name.lowercased().contains(search.lowercased())) }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.