难以理解复杂的swift关联类型声明
我看到下面的代码行在难以理解复杂的swift关联类型声明,swift,generics,types,protocols,Swift,Generics,Types,Protocols,我看到下面的代码行在 关联类型索引:\u RandomAccessIndexable,双向集合 =默认随机访问索引 我知道associatedtype是协议的类型别名,我知道如何在简单的情况下解释它 但是有人能给我解释一下我在swift github存储库中看到的代码行吗?这意味着关联的类型索引必须符合 \u RandomAccessIndexable和双向收集,默认情况下为defaultrandomAccessIndexes,除非另有声明(或推断)(其中Self是采用协议的实际类型) 例如:
关联类型索引:\u RandomAccessIndexable,双向集合
=默认随机访问索引
我知道associatedtype
是协议的类型别名,我知道如何在简单的情况下解释它
但是有人能给我解释一下我在swift github存储库中看到的代码行吗?这意味着关联的类型
索引必须符合
\u RandomAccessIndexable
和双向收集
,默认情况下为defaultrandomAccessIndexes
,除非另有声明(或推断)(其中Self
是采用协议的实际类型)
例如:
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>
struct MyIndex:可比{
var值:Int16
静态函数==(lhs:MyIndex,rhs:MyIndex)->Bool{
返回lhs.value==rhs.value
}
静态函数布尔{
返回lhs.value字符串{
返回“我是元素(position.value)”
}
func index(在i:MyIndex之后)->MyIndex{
guard i!=endIndex else{fatalError(“无法增加endIndex”)}
返回MyIndex(值:i.value+1)
}
func index(在i:MyIndex之前)->MyIndex{
guard i!=startIndex else{fatalError(“无法减少startIndex”)}
返回MyIndex(值:i.value-1)
}
}
设coll=MyCollectionType()
设i=coll.index
打印(类型(of:i))//DefaultRandomAccessIndex
MyCollectionType
是
RandomAccessCollection
,使用自定义索引类型MyIndex
。
它没有定义自己的索引
方法或索引
类型,
因此,索引
成为默认关联类型,
和
是一种默认的协议扩展方法,RandomAccessCollection
您的答案与往常一样令人惊叹!!非常感谢!!
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>