[英]How to make a constrained extension of Collection generic in Swift?
Context语境
I have a class Profile
which conforms to protocol Entity
.我有一个符合协议
Entity
的类Profile
。 I am also adding a search method to all Swift Collections
where the Element is a Profile
.我还向所有 Element 是
Profile
的Swift Collections
添加了一个搜索方法。
However, I would like to make this generic to support not only Profile
but every object conforming to Entity
.但是,我想让这个泛型不仅支持
Profile
,而且支持符合Entity
的每个对象。
Code代码
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())) }
}
}
Question题
How can I make the search method generic to support all objects conforming to Entity
?如何使搜索方法通用以支持符合
Entity
的所有对象?
first, you should change the extension to the below code首先,您应该将扩展名更改为以下代码
extension Collection where Iterator.Element: Entity
next, change the return type of the method to接下来,将方法的返回类型更改为
func searched(with search: String) -> [Iterator.Element]
Finally, the extension can be like this:最后,扩展可以是这样的:
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.