sal*_*qui 6 protocols ios swift
我想使用满足 OR ( || ) 约束的默认实现来扩展协议。
class A { }
class B { }
protocol SomeProtocol { }
/// It will throw error for ||
extension SomeProtocol where Self: A || Self: B {
}
Run Code Online (Sandbox Code Playgroud)
您不能使用 OR 扩展协议,因为您不能在 if let 中执行此操作,因为这样编译器会推断 self 或 var 的类型,因此如果它符合 2 种类型,则编译器不知道什么类型是自我。
(当你输入 self. 或任何 var. 编译器总是知道编译器类型中的 var 是什么类型,在这种情况下它会在运行时)。所以最简单的方法是让这两种类型符合一个协议并对该协议进行扩展。所以编译器知道 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 {
}
Run Code Online (Sandbox Code Playgroud)
此外,如果您想将扩展应用于这两种类型,则必须一一进行。
extension A: SomeProtocol { }
extension B: SomeProtocol { }
Run Code Online (Sandbox Code Playgroud)
// 愚蠢的例子:(在这种情况下并不是很有用,但它只是展示如何使 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()
Run Code Online (Sandbox Code Playgroud)