【问题标题】:Index of specific instance in swift array/collectionswift数组/集合中特定实例的索引
【发布时间】:2017-08-29 01:37:27
【问题描述】:

我的操场上有以下代码:

let array = [3,3]
let first = array.first!
let last = array.last!

let indices = [array.index(of: first)!, array.index(of: last)!]
print(indices) // This prints [0,0]

我知道“index(of:)”方法只是从数组中抓取第一个匹配的实例,这样效率更高,但我想知道是否有一种方法可以根据以下事实来抓取最后一个索引我从“array.last”中得到了值。

另外,如果我有以下情况:

let lotsOfThrees = [3,3,3,3,3,3,3]
let fourthThree = lotsOfThrees[3]
// Write code to return the index of "fourthThree" (possibly based on memory address)

我想知道是否有办法根据内存地址执行此操作,但老实说不确定。

【问题讨论】:

  • 我不明白你想做什么; “fourthThree”的索引是3 - 你已经有了。同样,在您的第一个代码中,前 3 个的索引是 0,最后一个的索引是 array.count-13 是一个值,所以数组中没有具体的“3”;它们都是一样的。
  • 嗯,我想知道是否有办法将参考文献联系在一起。就像我执行一些其他操作,或者将这些值传递给一个函数,因此我不知道“fourthThree”是索引 3,我只知道它是一个带有一些内存地址的 3。有没有办法将它与“lotsOfThrees”数组中的第四个对象相关联。最好带有库功能。我基本上想知道是否有任何库函数可以让我传回 array.last 并将其与 array.first 区分开来,如果它们具有相同的值
  • 你为什么需要这个?你实际上想用这个解决什么问题?
  • 我正在尝试实现一种解决方案,该解决方案将处理已排序或未排序的数组以解决“双和”问题。当有重复值时,我需要返回值的不同索引。
  • 我不明白为什么你需要使用indexOf 来解决二和问题

标签: arrays swift memory collections


【解决方案1】:

您可以通过反转数组来获取元素的 last 索引,然后获取 first 出现的索引。原始数组中最后一个元素的索引则为(反转数组中第一次出现的索引)-(数组大小)- 1. 将其放在扩展方法中以增加乐趣。

extension Array<T> {   
    func lastIndex(of item: T) -> Int? {
        if let lastIndex = self.reverse().index(of: item) {
            return self.count() - lastIndex - 1
        } else {
            return nil
        }
    }
}

【讨论】:

    【解决方案2】:

    我建议使用enumerated()filter 将索引与您要查找的值配对:

    let lotsOfThrees = [3, 3, 3, 3, 3, 3, 3]
    let threesAndIndices = lotsOfThrees.enumerated().filter { $1 == 3 }
    print(threesAndIndices)
    
    [(offset: 0, element: 3), (offset: 1, element: 3), (offset: 2, element: 3), (offset: 3, element: 3), (offset: 4, element: 3), (offset: 5, element: 3), (offset: 6, element: 3)]
    
    // find index of last three
    print(threesAndIndices.last!.offset)
    
    6
    
    // find index of 4th three
    print(threesAndIndices[4 - 1].offset)
    
    3
    

    你应该检查数组的大小,而不是假设有这样的最后一个值:

    let values = [1, 3, 2, 4, 1, 3, 3, 4, 1]
    let threesAndIndices = values.enumerated().filter { $1 == 3 }
    
    // find index of last three
    if let last = threesAndIndices.last {
        print("index of last three is \(last.offset)")
    } else {
        print("there are no threes")
    }
    
    index of last three is 6
    
    // find index of 4th three
    let nth = 4
    if nth > threesAndIndices.count {
        print("there aren't \(nth) threes")
    } else {
        let index = threesAndIndices[nth - 1].offset
        print("the index of three #\(nth) is \(index)")
    }
    
    there aren't 4 threes
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 2018-12-23
      • 2018-05-09
      • 1970-01-01
      • 2019-07-17
      相关资源
      最近更新 更多