How to stop enumerateObjectsUsingBlock Swift

后端 未结 5 510
慢半拍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:03

    Just stop = true

    Since stop is declared as inout, swift will take care of mapping the indirection for you.

    0 讨论(0)
  • 2020-12-14 16:09

    since XCode6 Beta4, the following way can be used instead:

    let array: NSArray = // the array with some elements...
    
    array.enumerateObjectsUsingBlock( { (object: AnyObject!, idx: Int, stop: UnsafePointer<ObjCBool>) -> Void in
    
            // do something with the current element...
    
            var shouldStop: ObjCBool = // true or false ...
            stop.initialize(shouldStop)
    
            })
    
    0 讨论(0)
  • 2020-12-14 16:11

    In Swift 1:

    stop.withUnsafePointer { p in p.memory = true }
    

    In Swift 2:

    stop.memory = true
    

    In Swift 3 - 4:

    stop.pointee = true
    
    0 讨论(0)
  • 2020-12-14 16:21

    This has unfortunately changed every major version of Swift. Here's a breakdown:

    Swift 1

    stop.withUnsafePointer { p in p.memory = true }
    

    Swift 2

    stop.memory = true
    

    Swift 3

    stop.pointee = true
    
    0 讨论(0)
  • 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
        }
    }
    
    0 讨论(0)
提交回复
热议问题