检查元素错误的索引

时间:2018-04-13 15:44:50

标签: arrays swift indexof any

我想检查数组中元素的索引:

var arr: [Any] = ["st","er","gh", 2, 5,"jk", 78 ]
print(arr.index(of: 2))

但是我收到了错误:

error: cannot invoke 'index' with an argument list of type '(of: Any)'
note: expected an argument list of type '(of: Self.Element)'

为什么控制台会抛出这个以及如何修复它?

2 个答案:

答案 0 :(得分:2)

为了使用索引(of :),必须采用Equatable协议

试试这段代码

   var arr: [Any] = ["st","er","gh", 2, 5,"jk", 78 ]
        print(arr.index(where: { (item) -> Bool in
            (item as? Int ) == 2
        }))

答案 1 :(得分:1)

在异构数组中,您必须使用index(where API并检查元素的类型:

let arr: [Any] = ["st","er","gh", 2, 5,"jk", 78 ]
if let index = arr.index(where: { $0 as? Int == 2 }) {
   print(index)
}