How to stop enumerateObjectsUsingBlock Swift

2019-01-24 00:16发布

问题:

How do I stop a block enumeration?

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

I know in obj-c you do this:

    [myArray enumerateObjectsUsingBlock:^(id *myObject, NSUInteger idx, BOOL *stop) {
        *stop = YES;
    }];

回答1:

In Swift 1:

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

In Swift 2:

stop.memory = true

In Swift 3 - 4:

stop.pointee = true


回答2:

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


回答3:

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)

        })


回答4:

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
    }
}


回答5:

Just stop = true

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