检查元素错误的索引
Checking index of element error
我想检查数组中元素的索引:
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)'
为什么控制台向我抛出这个问题以及如何解决它?
在异构数组中,您必须使用 index(where
API 并检查元素的类型:
let arr: [Any] = ["st","er","gh", 2, 5,"jk", 78 ]
if let index = arr.index(where: { [=10=] as? Int == 2 }) {
print(index)
}
为了使用 index(of:) 必须采用 Equatable 协议
试试这个代码
var arr: [Any] = ["st","er","gh", 2, 5,"jk", 78 ]
print(arr.index(where: { (item) -> Bool in
(item as? Int ) == 2
}))
我想检查数组中元素的索引:
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)'
为什么控制台向我抛出这个问题以及如何解决它?
在异构数组中,您必须使用 index(where
API 并检查元素的类型:
let arr: [Any] = ["st","er","gh", 2, 5,"jk", 78 ]
if let index = arr.index(where: { [=10=] as? Int == 2 }) {
print(index)
}
为了使用 index(of:) 必须采用 Equatable 协议
试试这个代码
var arr: [Any] = ["st","er","gh", 2, 5,"jk", 78 ]
print(arr.index(where: { (item) -> Bool in
(item as? Int ) == 2
}))