gpt4 book ai didi

swift - 协议(protocol)中的 associated(typealias) 类型和 Self 如何工作?

转载 作者:可可西里 更新时间:2023-11-01 01:00:06 25 4
gpt4 key购买 nike

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

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

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

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

typealias Element = Self

非常感谢。

最佳答案

Pro1

写这个

protocol Pro1 {
typealias Element
}

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

Pro2

添加这个

protocol Pro2: Pro1 {
typealias Element = Self
}

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

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

向 Pro1 添加方法

让我们在 Pro1 中声明 2 个将使用 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 因为 String 不同于 Foo

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

}
}

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

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

}
}

关于swift - 协议(protocol)中的 associated(typealias) 类型和 Self 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35473218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com