gpt4 book ai didi

swift - Swift 中的关联类型

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:23 26 4
gpt4 key购买 nike

swift编程语言中的关联类型是什么?它们的用途是什么?

根据 swift 编程语言书:

When defining a protocol, it is sometimes useful to declare one or more associated types as part of the protocol’s definition. An associated type gives a placeholder name (or alias) to a type that is used as part of the protocol. The actual type to use for that associated type is not specified until the protocol is adopted. Associated types are specified with the typealias keyword.

上面的文字我不是很清楚。如果您能用示例解释关联类型,将会有很大帮助。

另外,为什么将关联类型声明为协议(protocol)定义的一部分很有用?

最佳答案

您有一个协议(protocol),它定义了实现类型必须提供的方法和属性。其中一些方法/属性使用或返回与实现协议(protocol)的类型不同的类型的对象。因此,例如,如果您有一个协议(protocol)来定义某些类型的对象集合,您可以定义一个关联类型来定义集合的元素。

假设我想要一个协议(protocol)来定义一个 Stack,但是 Stack 是什么?没关系,我只是使用关联类型来充当占位符。

protocol Stack
{
// typealias Element - Swift 1
associatedtype Element // Swift 2+
func push(x: Element)
func pop() -> Element?
}

在上面的 Element 中,是堆栈中任何对象的类型。当我实现堆栈时,我使用 typealias 来指定堆栈元素的具体类型。

class StackOfInt: Stack
{
typealias Element = Int // Not strictly necessary, can be inferred
var ints: [Int] = []

func push(x: Int)
{
ints.append(x)
}

func pop() -> Int?
{
var ret: Int?
if ints.count > 0
{
ret = ints.last
ints.removeLast()
}
return ret
}
}

在上面,我定义了一个实现Stack的类,并且说对于这个类,Element实际上是Int。但是,人们经常省略 typealias,因为可以从方法实现中推断出 Element 的具体类型。例如在这种情况下,编译器可以查看 push() 的实现,并从参数类型了解 Element == Int

关于swift - Swift 中的关联类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35065127/

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