enumerateObjectsUsingBlock in Swift

后端 未结 4 1127
孤城傲影
孤城傲影 2021-02-05 02:10

I am trying to iterate through an array using enumerateObjectsUsingBlock to fetch data. How to use enumerateObjectsUsingBlock in Swift ? Please help me with an example.

4条回答
  •  再見小時候
    2021-02-05 02:47

    The existing answers can achieve what has been asked in the question. Also, you can write an extension to Array class and add similar method as -

    extension Array{
    func enumerateObject(_ block : (Any, Int,inout Bool)-> Void){
        var stop = false
        for (index, aValue) in self.enumerated(){
            block(aValue,index,&stop);
        }
    }
    

    //uses

    let numArr = [2,4,7,8,9];
    numArr.enumerateObject { (aValue, index, stop) in
        let value = aValue as! Int
        if !stop{
            print("At index \(index) value \(value)");
        }  
        if value == 7{
            print(value);
            stop = true;    
        }
    
    }
    

提交回复
热议问题