我看到這樣的例子很多下面的格式是什麼「其中自我」的協議擴展
是什麼協議擴展where Self
extension Protocolname where Self: UIViewController
什麼是where Self
這裏指的是,找不到關於這個的文檔。
我看到這樣的例子很多下面的格式是什麼「其中自我」的協議擴展
是什麼協議擴展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沒有獲得咩擴展功能。
let i = Obj();
i.blah();
但是,下面的工作。
let j = Foo();
j.blah();
換句話說,Meh.blah()
只提供給那些UIViewController
類型的類。
這裏是說明一個例子有什麼用,其中自我:UIViewController中
protocol SBIdentifiable {
static var sbIdentifier: String { get }
}
extension SBIdentifiable where Self: UIViewController {
static var sbIdentifier: String {
return String(describing: self)
}
}
extension UIVieWcontroller: SBIdentifiable { }
class ViewController: UIViewController {
func loadView() {
/*Below line we are using the sbIdentifier which will return the
ViewController class name.
and same name we would mentioned inside ViewController
storyboard ID. So that we do not need to write the identifier everytime.
So here where Self: UIViewController means it will only conform the protocol of type UIViewController*/
let viewController = self.instantiateViewController(withIdentifier:
self.sbIdentifier) as? SomeBiewController
}
}
感謝布蘭登。現在我懂了。 – Mini2008