用于查找自定义类型索引的数组扩展

时间:2018-03-13 00:22:21

标签: arrays swift

如何为Array编写扩展名以查找特定类型值的索引?

我希望该方法的行为与index(of: Element)调用相同。

到目前为止:

extension Array {
    func index(of fruit: Fruit) -> Int {
        for item in self {
            if item == fruit {
            //return the number 
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以扩展Array并创建一个泛型方法来返回元素属于特定类型的第一个索引:

extension Array {
    func index<T>(with type: T.Type) -> Index? {
        return index { $0 is T }
    }
}
struct Fruit { }

let objects: [Any] = [1,2,Fruit(),"leedex"]
objects.index(with: Fruit.self)   // 2
相关问题