我有一个名为 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/