arrays - 向后快速搜索数组

标签 arrays swift

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

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

最佳答案

很简单:

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

关于arrays - 向后快速搜索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33153438/

相关文章:

ios - 如何复合函数并持久化进度

iOS Pusher 客户端不会自动重新连接

javascript - 我的代码中有一个错误

C:复制结构/数组元素

javascript - 无法读取 JavaScript 中未定义数组错误的属性长度?

javascript - 添加到javascript中复杂类型的数组

ios - 小 View 在多个 View 上实时显示数据

swift - Xcode快速在Firebase数据更新上进行内存填充

ios - 无法在委托(delegate)回调方法中更新文本字段

c - 段错误: 11 when trying to run a C file that calculates and stores all combinations of a binary string in an array