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

考虑:

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类型的类.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...