在 Swift 数组中查找多次包含相同对象的对象

Find an object in Swift Array which has the same object multiple times in it

我正在为 Swift' Array 寻找 - [NSArray indexOfObject:inRange:] 的替代品。我要做的基本上是以下内容:

NSArray *A = @[@1, @3, @5, @4, @3];
NSUInteger cursor = 0;
while (YES) {
    NSUInteger res = [A indexOfObject:@3 inRange:NSMakeRange(cursor, A.count - cursor)];
    if (res == NSNotFound) {
        break;
    }
    NSLog(@"found 3 at %@", @(res));
    cursor = res + 1;
}

但我似乎无法找到一种方法来使用 Swift 数组从某个索引开始搜索。我当然可以创建子数组,但是在 Swift?

中有更好的方法吗?

数组切片是解决此问题的自然方式:

let numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3]
let range = 4...6
let desiredNumber = 2
let indexOfDesiredNumberInRange = numbers[range].index(of: desiredNumber)

print(indexOfDesiredNumberInRange as Any) // => Optional(4)

由于 ArraySlice 只是源 Array 的同一后备存储的视图,因此不会进行无用的复制

我假设您正在尝试获取您要查找的对象的所有索引。这是一个更好的方法

let arr = [1,2,3,4,3,5,6,7,8]

for (num, index) in test.enumerated() {
    if num == 3 {
        print("found 3 at \(index)")
    }
}

为您提供索引的另一种方式:

arr.enumerated().filter { (_, num) -> Bool in
    num == 3
}.map { [=11=].offset }