[英]Make Collection conform to custom protocol
I want to add a generic parameter for all collection type that has isEmpty
so they can also have isNotEmpty
When I try to make Collection
conform to Occupiable
I got an compile error 我想为所有具有
isEmpty
集合类型添加一个通用参数,因此它们也可以具有isNotEmpty
尝试使Collection
符合Occupiable
出现编译错误
error here : Extension of protocol 'Collection' cannot have an inheritance clause
错误:协议“集合”的扩展不能有继承子句
also String
conform to a protocol that inherent from Array so can we just remove extension String: Occupiable { }
once we found a solution for the issue above ? String
也符合Array固有的协议,因此一旦找到上述问题的解决方案,我们是否可以删除extension String: Occupiable { }
?
// Anything that can hold a value (strings, arrays, etc)
protocol Occupiable {
var isEmpty: Bool { get }
var isNotEmpty: Bool { get }
}
// Give a default implementation of isNotEmpty, so conformance only requires one implementation
extension Occupiable {
var isNotEmpty: Bool {
return !isEmpty
}
}
extension String: Occupiable { }
// error here : Extension of protocol 'Collection'
// cannot have an inheritance clause
extension Collection: Occupiable { }
Here you have created Occupiable protocol with isEmpty and isNotEmpty variables so when we implement protocol in any class these two variable need to declare to fullfill protocol. 在这里,您使用isEmpty和isNotEmpty变量创建了Occupiable协议,因此当我们在任何类中实现协议时,都需要声明这两个变量以完全填充协议。 but here you already declare isNotEmpty variable inside Occupiable's extension so now only one isEmpty compulsory in class where we implement protocol.
但是在这里您已经在Occupiable的扩展程序中声明了isNotEmpty变量,因此现在在我们实现协议的类中只有一个isEmpty强制性的。 so isEmpty inside Collection Protocol so we need to extend protocal.
所以在收集协议里面是isEmpty,所以我们需要扩展协议。 but it work in String because string is struct .
但是它在String中工作,因为string是struct。
you need to code for Collection like: 您需要为Collection编写如下代码:
extension Collection where Self : Occupiable {}
You need to set a constraint on conformance. 您需要设置一致性约束。 This will fix the error.
这将修复错误。
extension Collection where Self: Occupiable { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.