既然我已经学习了 Swift(达到了一个合理的水平),我正试图掌握标准库,但实际上它对我来说主要是 ελληνικά!
所以一个具体的问题:我有一个字符串数组,我可以在其上调用 reverse()。
let arr = ["Mykonos", "Rhodes", "Naxos"].reverse()
现在我天真地以为我会从中取回一种数组。 (例如,Ruby 有一个类似的方法,您可以传递一个数组并返回一个数组)
但是 arr 现在实际上是类型
ReverseRandomAccessCollection<Array<String>>
实际上是一个结构体,符合CollectionType:
public struct ReverseRandomAccessCollection<Base : CollectionType where Base.Index : RandomAccessIndexType> : _ReverseCollectionType
这意味着我可以这样做:
for item in arr {
print(item)
}
可是我做不到
print(arr[0])
为什么要这样设计?
Swift 中的字典也实现了 CollectionType,所以我可以这样做:
let dict = ["greek" : "swift sometimes", "notgreek" : "ruby for this example"].reverse()
但字典不像数组那样有序,所以为什么我可以在字典上调用 reverse()?
如果有人能指出我可以阅读和改进我的 Swift stdlib foo 的方向,我将加分,Eυχαριστώ!
最佳答案
这是对时间和内存的性能优化。
ReverseRandomAccessCollection
显示了
原始数组倒序,无需创建新数组
并复制所有元素(只要原始数组不是
突变)。
您可以访问带下标的反转元素:
let el0 = arr[arr.startIndex]
let el2 = arr[arr.startIndex.advancedBy(2)]
或
for i in arr.indices {
print(arr[i])
}
你也可以显式地创建一个数组
let reversed = Array(["Mykonos", "Rhodes", "Naxos"].reversed())
字典 也是键/值对的序列。在
let dict = ["greek" : "swift sometimes", "notgreek" : "ruby for this example"].reverse()
调用了一个完全不同的reversed()
方法:
extension SequenceType {
/// Return an `Array` containing the elements of `self` in reverse
/// order.
///
/// Complexity: O(N), where N is the length of `self`.
@warn_unused_result
public func reversed() -> [Self.Generator.Element]
}
结果是一个数组,其中包含字典的键/值对 以相反的顺序。但这用途有限,因为订单 字典中的键/值对可以是任意的。
关于arrays - 为什么Swift标准库中的reverse()函数会返回ReverseRandomAccessCollection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43255124/