How to stop enumerateObjectsUsingBlock Swift

后端 未结 5 521
慢半拍i
慢半拍i 2020-12-14 15:26

How do I stop a block enumeration?

    myArray.enumerateObjectsUsingBlock( { object, index, stop in
        //how do I stop the enumeration in here??
    })         


        
5条回答
  •  心在旅途
    2020-12-14 16:23

    The accepted answer is correct but will work for NSArrays only. Not for the Swift datatype Array. If you like you can recreate it with an extension.

    extension Array{
        func enumerateObjectsUsingBlock(enumerator:(obj:Any, idx:Int, inout stop:Bool)->Void){
            for (i,v) in enumerate(self){
                var stop:Bool = false
                enumerator(obj: v, idx: i,  stop: &stop)
                if stop{
                    break
                }
            }
        }
    }
    

    call it like

    [1,2,3,4,5].enumerateObjectsUsingBlock({
        obj, idx, stop in
    
        let x = (obj as Int) * (obj as Int)
        println("\(x)")
    
        if obj as Int == 3{
            stop = true
        }
    })
    

    or for function with a block as the last parameter you can do

    [1,2,3,4,5].enumerateObjectsUsingBlock(){
        obj, idx, stop in
    
        let x = (obj as Int) * (obj as Int)
        println("\(x)")
    
        if obj as Int == 3{
            stop = true
        }
    }
    

提交回复
热议问题