为一个或另一个扩展具有多个约束的协议 - Swift



我想使用满足 OR (||( 约束的默认实现来扩展协议。

class A { }
class B { }
protocol SomeProtocol { }
/// It will throw error for || 
extension SomeProtocol where Self: A || Self: B { 
}

你不能用OR扩展协议,因为你不能在if let中这样做,因为有了这个编译器推断self或var的类型,所以如果它符合2种类型,编译器不知道self是什么类型。

(当你键入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()

最新更新