我看到了很多下面格式的例子

extension Protocolname where Self: UIViewController

协议扩展中的where 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类型的类.

Swift相关问答推荐

如何让CTFontCreateUIFontForLanguage与汉字和表情包协同工作?

体积单位从夸脱转换为杯似乎关闭了

从后台线程获取@发布属性的值(不更改它)是正确的吗?

SwiftUI如何能够在Text中使用字符串字面量来创建LocalizedStringKey?

当字符串包含 \r\n 时,NSRegularExpression 不起作用

Swift Random Float Fatal Error:在无限范围内没有均匀分布

确定路径是否相交的有效方法

签署GoogleSignIn-GoogleSignIn需要开发团队

您可以在运行时访问 Picker 元素并更改它们的 colored颜色 吗

Swift初始化具有可变ID的重复值数组

ZStack 中的 ProgressView 与 View 的行为不同

不要从 NumberFormatter 获取货币符号

Vapor, fluent 使用 PostgreSQL 保存/创建复杂模型

如何防止 UITableViewCell 移动(Swift 5)

在 Swift 4 中实现自定义解码器

为什么'nil' 与 Swift 3 中的 'UnsafePointer' 不兼容?

自动布局:获取 UIImageView 高度以正确计算单元格高度

如何从 UITableViewCell 类中引用 UITableViewController?

两个 Date 对象之间的所有日期 (Swift)

自定义 Google 登录按钮 - iOS