I am creating a class in swift work as a container of a set of protocols. Below is the source code. The KeyValueObserverDelegate protocol is added in KeyValueObserverService class by addObserver() method. The problem happens on removeObserver() method, the line is index = array.indexOf($0 == observer).
I got an error:
anonymous closure argument not contained in a closure.
I don't know what wrong with my class. How can I get the index of an object from an array?
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?)
}