swift – 协议扩展中的’自我’是什么?

前端之家收集整理的这篇文章主要介绍了swift – 协议扩展中的’自我’是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我看到了很多以下格式的例子

什么是Self在协议扩展中的位置

扩展Protocolname其中Self:UIViewController

Self在这里指的是什么,找不到关于此的文档.

该语法是: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID521

考虑:

  1. protocol Meh {
  2. func doSomething();
  3. }
  4.  
  5. //Extend protocol Meh,where `Self` is of type `UIViewController`
  6. //func blah() will only exist for classes that inherit `UIViewController`.
  7. //In fact,this entire extension only exists for `UIViewController` subclasses.
  8.  
  9. extension Meh where Self: UIViewController {
  10. func blah() {
  11. print("Blah");
  12. }
  13.  
  14. func foo() {
  15. print("Foo");
  16. }
  17. }
  18.  
  19. 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`.
  20. func doSomething() {
  21. print("Do Something");
  22. }
  23. }
  24.  
  25. 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()`.
  26. func doSomething() {
  27. print("Do Something");
  28. }
  29. }

以下将给出编译器错误,因为Obj无法访问Meh扩展函数.

  1. let i = Obj();
  2. i.blah();

但是下面的方法会奏效.

  1. let j = Foo();
  2. j.blah();

换句话说,Meh.blah()仅适用于UIViewController类型的类.

猜你在找的Swift相关文章