swift搜索阵列向后

时间:2015-10-15 16:08:50

标签: arrays swift

我有一个我想向后搜索的数组。我对原始数组的结果索引感兴趣,而不是实际值。如何将ReverseRandomAccessIndex转换为" normal"索引?

let arr = [1,2,3,4,5]
if let index = arr.reverse().indexOf(2) //index is ReverseRandomAccessIndex
{
 let searchvalue = arr.reverse()[index]
}

1 个答案:

答案 0 :(得分:2)

很简单:

let arr = [1, 2, 3, 4, 5]

if let index = arr.reverse().indexOf(2)
{
    let searchvalue = arr[index.base - 1]
}

base,如标准库中所定义:

    /// The successor position in the underlying (un-reversed)
    /// collection.
    ///
    /// If `self` is `advance(c.reverse.startIndex, n)`, then:
    /// - `self.base` is `advance(c.endIndex, -n)`.
    /// - if `n` != `c.count`, then `c.reverse[self]` is 
    ///   equivalent to `[self.base.predecessor()]`.
    public let base: Base