Swift中的关联类型

前端之家收集整理的这篇文章主要介绍了Swift中的关联类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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 Stack
{
    // typealias Element - Swift 1
    associatedtype Element // Swift 2+
    func push(x: Element)
    func pop() -> 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.但是,人们常常忽略了类型,因为可以从方法实现中推断出具体的Element类型.例如编译器可以查看push()的实现,并在这种情况下从Element == Int的参数类型中实现.

原文链接:https://www.f2er.com/swift/318715.html

猜你在找的Swift相关文章