问题描述
我想知道快速数组上的reversed()方法:
可变项= ["a","b","c"]items = items.reversed()
Apple文档中反向方法的签名说,它返回一个
ReversedRandomAccessCollection< Array< Element>>
可以将其分配回项目,而无需执行苹果医生所说的是什么
还是将来会带来问题?(因为编译器没有抱怨)
在Swift 3中,数组的3个reversed()重载.
- 将数组作为RandomAccessCollection处理,
默认情况下,
reversed()
选择RandomAccessCollection的重载并返回ReversedRandomAccessCollection.但是,当你写items = items.reversed()
您正在强迫RHS返回可转换为LHS的类型(
[String]
).因此,只会选择返回数组的第三个重载.该重载将复制整个序列(因此为O(n)),因此覆盖原始数组没有问题.
代替
items = items.reversed()
,它创建数组的副本,将其反转并复制回去,您可以使用变异函数items.reverse()
,可进行原位恢复而不复制阵列两次.I'm wondering about the reversed() method on a swift Array:
var items = ["a", "b", "c"] items = items.reversed()
the signature of the reversed method from the Apple doc says that it returns a
ReversedRandomAccessCollection<Array<Element>>
could that be assigned back to items without doing what the apple doc say which is
or would it give problem in the future? (since the compiler doesn't complain)
解决方案There are 3 overloads of reversed() for an Array in Swift 3:
- Treating the Array as a RandomAccessCollection,
func reversed() -> ReversedRandomAccessCollection<Self>
(O(1)) - Treating the Array as a BidirectionalCollection,
func reversed() -> ReversedCollection<Self>
(O(1)) - Treating the Array as a Sequence,
func reversed() -> [Self.Iterator.Element]
(O(n))
By default,
reversed()
pick the RandomAccessCollection's overload and return a ReversedRandomAccessCollection. However, when you writeitems = items.reversed()
you are forcing the RHS to return a type convertible to the LHS (
[String]
). Thus, only the 3rd overload that returns an array will be chosen.That overload will copy the whole sequence (thus O(n)), so there is no problem overwriting the original array.
Instead of
items = items.reversed()
, which creates a copy of the array, reverse that and copy it back, you could reach the same effect using the mutating functionitems.reverse()
, which does the reversion in-place without copying the array twice.这篇关于可能会带来什么麻烦呢?将reversed()组合到一个快速数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- Treating the Array as a RandomAccessCollection,