我正在快速工作中创建一个类,作为一组协议的容器。下面是源代码。 KeyValueObserverDelegate
协议是通过KeyValueObserverService
方法添加到addObserver()
类中的。问题发生在removeObserver()
方法上,该行是index = array.indexOf($0 == observer)
。
我收到一个错误:
闭包中不包含匿名闭包参数。
我不知道我班上怎么了。如何从数组中获取对象的索引?
class KeyValueObserverService{
private var observerList:Dictionary<String, [KeyValueObserverDelegate]> = Dictionary()
func addObserver(key:String, observer:KeyValueObserverDelegate){
var array:Array<KeyValueObserverDelegate>?
if observerList.keys.contains(key){
array = observerList[key]
} else {
array = Array<KeyValueObserverDelegate>()
self.observerList[key] = array
}
array?.append(observer)
}
func updateValueForKey(key:String, value:AnyObject?){
let array = self.observerList[key];
if array == nil{
return
}
for element in array!{
element.valueChanged(value)
}
}
func removeObserver(key:String, observer:KeyValueObserverDelegate){
if self.observerList.keys.contains(key) == false{
return
}
var array:[KeyValueObserverDelegate] = self.observerList[key]!;
let index:Int?
index = array.indexOf($0 == observer)
array.removeAtIndex(index!)
}
}
protocol KeyValueObserverDelegate :class{
func valueChanged(value:AnyObject?)
}
最佳答案
仔细阅读错误消息
...不包含在闭包中
根据定义,闭包封闭在一对花括号中
array.indexOf({$0 == observer})
或尾随闭包语法
array.indexOf{$0 == observer}
编辑:
由于默认情况下协议不符合
Equatable
,因此请使用身份运算符array.indexOf{$0 === observer}