[英]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.