swift - 难以理解复杂的快速关联类型声明

标签 swift generics types protocols

我在 swift github repository 看到了下面的代码行

associatedtype Indices : _RandomAccessIndexable, BidirectionalCollection
    = DefaultRandomAccessIndices<Self>

我知道 associatedtype 是协议(protocol)的类型别名,我知道如何在简单情况下解释它

但是有人可以向我解释一下我从 swift github 存储库中看到的代码行吗?

最佳答案

这意味着关联类型Indices必须符合 _RandomAccessIndexableBidirectionalCollection , 默认为 DefaultRandomAccessIndices<Self>除非以其他方式声明(或推断)(其中 Self 是采用协议(protocol)的实际类型)。

例子:

struct MyIndex : Comparable {
    var value : Int16

    static func ==(lhs : MyIndex, rhs : MyIndex) -> Bool {
        return lhs.value == rhs.value
    }
    static func <(lhs : MyIndex, rhs : MyIndex) -> Bool {
        return lhs.value < rhs.value
    }
}

struct MyCollectionType : RandomAccessCollection {

    var startIndex : MyIndex { return MyIndex(value: 0) }
    var endIndex : MyIndex { return MyIndex(value: 3) }

    subscript(position : MyIndex) -> String {
        return "I am element #\(position.value)"
    }

    func index(after i: MyIndex) -> MyIndex {
        guard i != endIndex else { fatalError("Cannot increment endIndex") }
        return MyIndex(value: i.value + 1)
    }
    func index(before i: MyIndex) -> MyIndex {
        guard i != startIndex else { fatalError("Cannot decrement startIndex") }
        return MyIndex(value: i.value - 1)
    }
}

let coll = MyCollectionType()
let i = coll.indices
print(type(of: i)) // DefaultRandomAccessIndices<MyCollectionType>

MyCollectionType是一个(最小的?)实现 RandomAccessCollection , 使用自定义索引类型 MyIndex . 它没有定义自己的 indices方法或 Indices类型, 这样Indices成为默认的关联类型, 和 indices RandomAccessCollection 的默认协议(protocol)扩展方法.

关于swift - 难以理解复杂的快速关联类型声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43221646/

相关文章:

java - 不需要的通用参数

types - 从C查询Lua用户数据类型

C# 比较 native 类型和可空类型(Int32 和 Int32?)

swift - fatal error : Unexpectedly found nil while unwrapping an Optional value SwiftUI AnimatedImage

swift - 如何调整导航栏文本中的字距调整?

ios - 来自任何地方的初始 View Controller

标量范围返回Long而不是Int

swift - iOS10 UserDefaults 文件位置/路径?

generics - 如何在泛型中强制使用子类/协议(protocol)

Java 选择性泛型