抱歉,我是编程的新手,我试着表达我想问的问题。请原谅我。 我在协议中看到过这样的东西。
protocol Pro1 {
typealias Element
// ...
}
protocol Pro2: Pro1 {
typealias Element = Self
// ...
}
协议中的 Element
,这个Element
是否相互关联?
我不明白以下表达的含义:
typealias Element = Self
非常感谢。
答案 0 :(得分:3)
写这个
protocol Pro1 {
typealias Element
}
您只是告诉我们会有一个名为Element
的类型。
添加此
protocol Pro2: Pro1 {
typealias Element = Self
}
您告诉编译器Element
将与实现Pro2
的类型相同。
是的,Element
和Pro1
中的Pro2
之间存在关系。
让我们声明在Element
Pro1
的两种方法
protocol Pro1 {
typealias Element
func a() -> Element
func b(elm: Element)
}
现在符合Pro1
的类就是这样。
class Foo: Pro1 {
func a() -> String {
return ""
}
func b(elm: String) {
}
}
正如您所看到的,编译器强制我们将a
的返回类型和b
的参数设置为相同类型。
现在让我们尝试将另一个类与Pro2相符合。同样Pro1
将强制我们声明方法a
和b
,其中a的返回类型等于b
的参数。
此外,Pro2
会强制我们将此类型设置为等于当前类型Boo
的类型。
因此,上一课将符合Pro2
,因为String
与Foo
不同
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) {
}
}