协议扩展中的“where self"是什么 [英] what is 'where self' in protocol extension
本文介绍了协议扩展中的“where self"是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到了很多以下格式的例子
I saw so many examples with below format
extension Protocolname where Self: UIViewController
协议扩展中的where Self
是什么.我找不到这方面的文档.
What is where Self
in protocol extension. I couldn't find the documentation on this.
推荐答案
考虑:
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 扩展函数,因此以下将给出编译器错误.
The below will give a compiler error because Obj doesn't have access to Meh extension functions.
let i = Obj()
i.blah()
但是下面的方法会起作用.
But the below will work.
let j = Foo()
j.blah()
换句话说,Meh.blah()
仅适用于 UIViewController
类型的类.
In other words, Meh.blah()
is only available to classes that are of type UIViewController
.
这篇关于协议扩展中的“where self"是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文