arrays - Swift Programming How to search an Array of [Any]--> Generic parameter 'C.Generator.Element' cannot be bound to non-@ob 错误

标签 arrays swift

您好,我正在尝试搜索包含各种对象的数组,但出现错误。

Generic parameter 'C.Generator.Element' cannot be bound to non-@ob

这是我正在使用的代码:

var arraySearching = [Any]()
arraySearching = ["this","that",2]
find(arraySearching, 2)

如何搜索类型为[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
}

一旦有了它,就可以使用它在 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 
}

关于arrays - Swift Programming How to search an Array of [Any]--> Generic parameter 'C.Generator.Element' cannot be bound to non-@ob 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29403088/

相关文章:

javascript - 更改阵列中的多个图像源

C++:尝试打印 const char* 数组时程序崩溃

ios - 从静态结构更新 tabbarcontroller 角标(Badge)

ios - Swift - 添加新部分时静态 TableView 单元格抛出索引超出范围错误

objective-c - 发送usb包osx

c++ - 数组初始化 - 有条件地

javascript - 从多维数组中删除重复的元素对

python - ReplyKeyboardMarkup 对 python 不起作用?

arrays - 数组名称被描述为字符串

ios - 如何更快地加载 MKMapView?