我的操场上有以下代码:
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)
我想知道是否有办法根据内存地址执行此操作,但老实说不确定。
答案 0 :(得分:0)
您可以通过反转数组,然后获取第一个出现的索引来获取元素的 last 索引。然后原始数组中的最后一个元素索引(反向数组中第一次出现的索引) - (数组的大小) - 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
}
}
}
答案 1 :(得分:0)
我建议使用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