ios - 从传递协议(protocol)实例的数组中删除对象

标签 ios arrays swift

我有一个名为 IdeaListener 的协议(protocol),以及扩展该协议(protocol)的元素数组。

private var ideaListeners: [IdeaListener]

我想创建一个扩展,以便从给定 IdeaProtocol 实例的数组中删除对象。

var myInstanceOfIdeaListener: IdeaListener
...
ideaListeners.removeObject(myInstanceOfIdeaListener)

我在网络上找到了许多解决方案,但没有一个能够接受协议(protocol)作为 removeObject 函数的参数。 为了实现这一点,我编写了这个扩展:

extension Array {

   mutating func removeObject(object: AnyObject) -> Element? {

    for (index, objectToCompare) in self.enumerate() {
        if let to = objectToCompare as? AnyObject where to == object {
            return removeAtIndex(index)
        }
    }
    return nil
  }
}

但是编译器说

Binary operator '==' cannot be applied to two 'AnyObject' operands.

为什么我不能使用 == 来比较两个 AnyObject?如何检查数组是否包含object

此外,我想改进这个函数,在开头添加类型检查,以检查object的类型是否实际上是数组中元素的类型。但我不确定如何编写这个概念。像这样的事情:

guard object is /*type of elements in array*/ else {
     return nil
}

如何获取数组中元素的类型?

最佳答案

你可以尝试这样的事情

    let a = ObjectOfProtocol()
    let b = ObjectNotOfProtocol()
    let c = [a,b]

    let d = c.filter { (x:AnyObject) -> Bool in

        return !x.conformsToProtocol(Protocol);
    }

    print("filtered array: \(d)") //should only show [ObjectNotOfProtocol]

这将删除数组中符合协议(protocol)的所有对象

因此,无需进行扩展,只需使用此过滤器即可

甚至可以将其添加为 method extension to the Protocol itself ,所以你可以使用类似 Protocol.filterFromArray(array) 的方法,如果你希望它只是一个方法调用而不是每次都写出过滤器,它将返回过滤掉协议(protocol)的所有对象的数组

关于ios - 从传递协议(protocol)实例的数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35742208/

相关文章:

ios - 自定义单元格图像作为 Swift 中的附件类型

ios - 使用 CoreLocation 获取最近的位置

iphone - UISegmentedControl 抛出异常

javascript - 我想按字母顺序生成唯一的字母键 |angularJs

arrays - 如何在swift中声明数组类型

arrays - 嵌套数组的行为不同

swift - 如何在 SwiftUI tvOS 中检测 'Click' 手势

ios - 使用 UIAlertController 阻塞循环

ios - NSPredicate 与 CNContact 不工作

ios - iOS 14 中 UIDocumentPickerViewController 的初始化