enumerateObjectsUsingBlock in Swift

后端 未结 4 1137
孤城傲影
孤城傲影 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:30

    The new enumerate function returns a tuple with indexer and value so you can get similar functionality to enumerateObjectsUsingBlock.

    func myBlock (index: Int, value: Int, inout stop: Bool) -> Void {
        println("Index: \(index) Value: \(value)")
        if index == 3 {
            stop = true
        }
    }
    
    var array = [1,2,3,4,5]
    
    for (index, value) in enumerate(array) {
        var stop = false;
        myBlock(index, value, &stop)
        if stop  {
            break;
        }
    }
    
    //Output...
    //Index: 0 Value: 1
    //Index: 1 Value: 2
    //Index: 2 Value: 3
    //Index: 3 Value: 4
    

    I imagine they haven't exposed enumerateObjectsUsingBlock as you can replicate the functionality with the above code.

    EDIT: Anonymous function was crashing my playground so used an inline function. Also added using stop variable for illustrative purposes.

提交回复
热议问题