嗨,我正在尝试使用各种对象搜索数组,虽然我收到错误.
通用参数'C.Generator.Element'不能绑定到非@ ob
这是我正在使用的代码:
var arraySearching = [Any]()
arraySearching = ["this","that",2]
find(arraySearching, 2)
Run Code Online (Sandbox Code Playgroud)
你如何搜索类型的数组[Any]
?
这是一个误导性错误消息,但问题是find
要求您正在搜索的集合的内容是Equatable
,而Any
不是.Any
事实上,你根本无法做太多事情,更不用说将它与其他类型的值等同起来.你必须将它转换为真实类型,然后使用它.
这在封闭中很容易做到,除了没有一个版本find
需要关闭.但是写一个很容易:
func find<C: CollectionType>(source: C, match: C.Generator.Element -> Bool) -> C.Index? {
for idx in indices(source) {
if match(source[idx]) { return idx }
}
return nil
}
Run Code Online (Sandbox Code Playgroud)
完成后,您可以使用它在以下数组中搜索特定类型的值Any
:
find(arraySearching) {
// cast the candidate to an Int, then compare (comparing an
// optional result of as? works fine, nil == 2 is false)
($0 as? Int) == 2
}
Run Code Online (Sandbox Code Playgroud)