可能会带来什么麻烦呢?将reversed()组合到一个快速数组中? [英] What trouble could bring assining reversed() to a swift array?

查看:59
本文介绍了可能会带来什么麻烦呢?将reversed()组合到一个快速数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道快速数组上的reversed()方法:

 可变项= ["a","b","c"]items = items.reversed() 

Apple文档中反向方法的签名说,它返回一个

ReversedRandomAccessCollection< Array< Element>>

可以将其分配回项目,而无需执行苹果医生所说的是什么

例如,要获取数组的反向版本,请从reversed()方法的结果中初始化一个新的Array实例.

还是将来会带来问题?(因为编译器没有抱怨)

解决方案

在Swift 3中,数组的3个reversed()重载.

  1. 将数组作为RandomAccessCollection处理,

    默认情况下, reversed()选择RandomAccessCollection的重载并返回ReversedRandomAccessCollection.但是,当你写

      items = items.reversed() 

    您正在强迫RHS返回可转换为LHS的类型( [String] ).因此,只会选择返回数组的第三个重载.

    该重载将复制整个序列(因此为O(n)),因此覆盖原始数组没有问题.


    代替 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

    For example, to get the reversed version of an array, initialize a new Array instance from the result of this reversed() method.

    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:

    1. Treating the Array as a RandomAccessCollection,
      func reversed() -> ReversedRandomAccessCollection<Self> (O(1))
    2. Treating the Array as a BidirectionalCollection,
      func reversed() -> ReversedCollection<Self> (O(1))
    3. 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 write

    items = 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 function items.reverse(), which does the reversion in-place without copying the array twice.

    这篇关于可能会带来什么麻烦呢?将reversed()组合到一个快速数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆