相关疑难解决方法(0)

为什么Swift标准库中的reverse()函数返回ReverseRandomAccessCollection?

现在我已经学会了Swift(达到一个合理的水平),我正试图掌握标准库,但实际上它主要是ελληνικά给我!

所以一个特定的问题:我有一个字符串数组,我可以调用reverse().

let arr = ["Mykonos", "Rhodes", "Naxos"].reverse()
Run Code Online (Sandbox Code Playgroud)

现在天真地我以为我会从中找回一种类型的阵列.(例如Ruby有一个类似的方法,你传递一个数组并返回一个数组)

但arr现在实际上是类型

ReverseRandomAccessCollection<Array<String>>
Run Code Online (Sandbox Code Playgroud)

这实际上是一个符合CollectionType的结构:

public struct ReverseRandomAccessCollection<Base : CollectionType where Base.Index : RandomAccessIndexType> : _ReverseCollectionType
Run Code Online (Sandbox Code Playgroud)

这意味着我可以这样做:

for item in arr {
  print(item)
}
Run Code Online (Sandbox Code Playgroud)

但我不能这样做

print(arr[0])
Run Code Online (Sandbox Code Playgroud)

为什么这样设计成这样?

Swift中的字典也实现了CollectionType,所以我可以这样做:

let dict = ["greek" : "swift sometimes", "notgreek" : "ruby for this example"].reverse()
Run Code Online (Sandbox Code Playgroud)

但字典不像数组一样排序,为什么我可以在dicts上调用reverse()?

奖励积分如果有人能指出我可以阅读的方向并改善我的Swift stdlib foo,Ευχαριστώ!

arrays standard-library swift

19
推荐指数
1
解决办法
7102
查看次数

标签 统计

arrays ×1

standard-library ×1

swift ×1