简体   繁体   English

如何从数组中快速获取对象索引

[英]How to get an object index from an array in swift

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. KeyValueObserverDelegate协议通过addObserver()方法添加到KeyValueObserverService类中。 The problem happens on removeObserver() method, the line is index = array.indexOf($0 == observer) . 问题发生在removeObserver()方法上,该行是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?)
}

Read the error message carefully 仔细阅读错误消息

...not contained in a closure ...不包含在闭包中

By definition a closure is enclosed in a pair of curly braces 根据定义,闭合用一对大括号括起来

array.indexOf({$0 == observer})

or with trailing closure syntax 或尾随闭包语法

array.indexOf{$0 == observer}

Edit: 编辑:

Since a protocol does not conform to Equatable by default use the identity operator 由于默认情况下协议不符合Equatable ,因此请使用身份运算符

array.indexOf{$0 === observer}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM