代码之家  ›  专栏  ›  技术社区  ›  Evgeniy Kleban

数组元素的快速返回索引

  •  0
  • Evgeniy Kleban  · 技术社区  · 8 年前

    我想编写一个函数,遍历数组并返回找到该元素的索引。

    类似于:

    extension Array {
    
        func elementIndexes<T>() -> [Int] {
    
            // if element is kind of class "T" add it to array [T] and then return
    
        }
    }
    

    然而,我没有成功。我该怎么做?

    3 回复  |  直到 7 年前
        1
  •  3
  •   Connor Neville    8 年前

    听起来,为了澄清措辞,您希望获取元素为T类型的所有索引。下面是数组上的扩展,可以实现这一点,并提供一个示例:

    extension Array {
    
        func indices<T>(ofType type: T.Type) -> [Int] {
            return self.enumerated().filter({ $0.element is T }).map({ $0.offset })
        }
    
    }
    
    struct TypeA { }
    struct TypeB { }
    
    let list: [Any] = [TypeA(), TypeB(), TypeB(), TypeA()]
    
    print(list.indices(ofType: TypeA.self)) // prints [0, 3]
    
        2
  •  2
  •   vadian    8 年前

    您可以过滤 indices 直接来说,这是 更通用 版本(学分至 Leo Dabus Hamish )

    extension Collection {
    
        func indices<T>(of type: T.Type) -> [Index] {
            return indices.filter { self[$0] is T }
        }
    }
    
        3
  •  1
  •   holex    7 年前

    这可能适用于您:

    extension Array {
    
        func indices<T>(of: T.Type) -> [Int] {
    
            return self.enumerated().flatMap { $0.element is T ? $0.offset : nil }
    
        }
    
    }
    

    或者,如果你想处理更传统的解决方案,那么这就是你的方式:

    extension Array {
    
        func indices<T>(of: T.Type) -> [Int] {
    
            var indices = [Int]()
    
            for (n, item) in self.enumerated() {
                if item is T {
                    indices.append(n)
                }
            }
    
            return indices
        }
    
    }
    

    与此测试阵列类似:

    let array: [Any] = [1, 2, "3", "4"]
    
    debugPrint(array.indices(of: String.self))
    

    两者在操场上呈现相同的输出,即:

    [2, 3]