作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我在 swift github repository 看到了下面的代码行
associatedtype Indices : _RandomAccessIndexable, BidirectionalCollection
= DefaultRandomAccessIndices<Self>
我知道 associatedtype
是协议(protocol)的类型别名,我知道如何在简单情况下解释它
但是有人可以向我解释一下我从 swift github 存储库中看到的代码行吗?
最佳答案
这意味着关联类型Indices
必须符合 _RandomAccessIndexable
和 BidirectionalCollection
, 默认为 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/
我想模拟这个函数: function getMetaData(key) { var deferred = $q.defer(); var s3 = vm.ini
我是一名优秀的程序员,十分优秀!