2015-10-15 64 views
3

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

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

'NormalIndex =(计数 - 1) - ReverseIndex',也许? – holex

+0

您无法直接获取索引。这是一个ReverseRandomAccessIndex。请参阅下面的答案。 – user965972

回答

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