协议中的关联(typealias)类型和Self如何工作?

时间:2016-02-18 05:01:49

标签: swift protocols type-alias

抱歉,我是编程的新手,我试着表达我想问的问题。请原谅我。 我在协议中看到过这样的东西。

protocol Pro1 {
    typealias Element
    // ...
}
protocol Pro2: Pro1 {
    typealias Element = Self
    // ...
}
协议中的

Element,这个Element是否相互关联?

我不明白以下表达的含义:

typealias Element = Self

非常感谢。

1 个答案:

答案 0 :(得分:3)

Pro1的

写这个

protocol Pro1 {
    typealias Element
}

您只是告诉我们会有一个名为Element的类型。

Pro2的

添加此

protocol Pro2: Pro1 {
    typealias Element = Self
}

您告诉编译器Element将与实现Pro2的类型相同。

是的,ElementPro1中的Pro2之间存在关系

向Pro1

添加方法

让我们声明在Element

中使用Pro1的两种方法
protocol Pro1 {
    typealias Element
    func a() -> Element
    func b(elm: Element)
}

符合Pro1

现在符合Pro1的类就是这样。

class Foo: Pro1 {
    func a() -> String {
        return ""
    }
    func b(elm: String) {
    }
}

正如您所看到的,编译器强制我们将a的返回类型和b的参数设置为相同类型

符合Pro2

现在让我们尝试将另一个类与Pro2相符合。同样Pro1将强制我们声明方法ab,其中a的返回类型等于b的参数。 此外,Pro2会强制我们将此类型设置为等于当前类型Boo的类型。

因此,上一课将符合Pro2,因为StringFoo不同

class Foo: Pro2 {
    func a() -> String { // <- compiler error
        return ""
    }
    func b(elm: String) { // <- compiler error

    }
}

但是,如果我们声明一个新类并将Element替换为Boo,那么它将起作用,因为两个协议的约束都得到满足。

class Boo: Pro2 {
    func a() -> Boo {
        return Boo()
    }
    func b(elm: Boo) {

    }
}