【问题标题】:How associated(typealias) type and Self in protocols work?协议中的关联(typealias)类型和 Self 是如何工作的?
【发布时间】:2016-02-18 05:01:49
【问题描述】:

对不起,我是编程新手,我试着表达我想问的问题。请原谅我。 我在协议中看到过类似的东西。

protocol Pro1 {
    typealias Element
    // ...
}
protocol Pro2: Pro1 {
    typealias Element = Self
    // ...
}

Element 在协议中,这个Element 是否相互关联?

而且我不明白下面的表达是什么意思:

typealias Element = Self

非常感谢。

【问题讨论】:

    标签: swift protocols type-alias


    【解决方案1】:

    专业版1

    写这个

    protocol Pro1 {
        typealias Element
    }
    

    你只是说会有一个名为Element的类型。

    专业版2

    添加这个

    protocol Pro2: Pro1 {
        typealias Element = Self
    }
    

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

    所以是的,Pro1Pro2 中的 Element 之间存在关系

    向 Pro1 添加方法

    让我们在Pro1 中声明两个将使用Element 的方法

    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) {
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多