我看到了很多下面格式的例子
extension Protocolname where Self: UIViewController
协议扩展中的where Self
是多少.我找不到这方面的文件.
我看到了很多下面格式的例子
extension Protocolname where Self: UIViewController
协议扩展中的where Self
是多少.我找不到这方面的文件.
考虑:
protocol Meh {
func doSomething()
}
// Extend protocol Meh, where `Self` is of type `UIViewController`
// func blah() will only exist for classes that inherit `UIViewController`.
// In fact, this entire extension only exists for `UIViewController` subclasses.
extension Meh where Self: UIViewController {
func blah() {
print("Blah")
}
func foo() {
print("Foo")
}
}
class Foo : UIViewController, Meh { //This compiles and since Foo is a `UIViewController` subclass, it has access to all of `Meh` extension functions and `Meh` itself. IE: `doSomething, blah, foo`.
func doSomething() {
print("Do Something")
}
}
class Obj : NSObject, Meh { //While this compiles, it won't have access to any of `Meh` extension functions. It only has access to `Meh.doSomething()`.
func doSomething() {
print("Do Something")
}
}
下面将给出一个编译器错误,因为Obj无法访问Meh扩展函数.
let i = Obj()
i.blah()
但下面的方法会奏效.
let j = Foo()
j.blah()
换句话说,Meh.blah()
只适用于UIViewController
类型的类.