[英]Extend a Protocol with Multiple Constraints for One OR the Other - Swift
我想使用满足OR(||)约束的默认实现来扩展协议。
class A { }
class B { }
protocol SomeProtocol { }
/// It will throw error for ||
extension SomeProtocol where Self: A || Self: B {
}
你不能用OR扩展协议,因为你不能在if中执行它,因为这样编译器会推断self或var的类型,所以如果它符合2种类型,编译器就不知道什么类型的自我。
(当您键入self。或任何var时,编译器始终知道编译器类型中的var类型,在这种情况下,它将在运行时)。 因此,最简单的方法是使2种类型符合协议并对该协议进行扩展。 因此,编译器知道self符合协议,并且他不关心Self的确切类型(但是您将只能使用协议中声明的属性)。
protocol ABType {
// Properties that you want to use in your extension.
}
class A: ABType, SomeProtocol { }
class B: ABType, SomeProtocol { }
protocol SomeProtocol { }
extension SomeProtocol where Self: ABType {
}
此外,如果您要将扩展应用于这两种类型,则必须逐个执行。
extension A: SomeProtocol { }
extension B: SomeProtocol { }
//愚蠢的例子:(在这种情况下并不是真的有用,但它只是为了说明如何使2个类符合协议并使用该协议中声明的方法并创建默认实现来扩展它。 )
protocol ABType {
func getName()
}
class AClass: ABType {
func getName() {
print ("A Class")
}
}
class BClass: ABType, someProtocol {
func getName() {
print ("B Class")
}
}
protocol someProtocol {
func anotherFunc()
}
extension someProtocol where Self: ABType {
func anotherFunc() {
self.getName()
}
}
let a = AClass()
// a.anotherFunc() <- Error, A cant call anotherFunc
let b = BClass()
b.anotherFunc()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.