How to stop enumerateObjectsUsingBlock Swift

2019-01-23 23:46发布

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

5条回答
别忘想泡老子
2楼-- · 2019-01-24 00:05

In Swift 1:

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

In Swift 2:

stop.memory = true

In Swift 3 - 4:

stop.pointee = true
查看更多
女痞
3楼-- · 2019-01-24 00:12

Just stop = true

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

查看更多
Fickle 薄情
4楼-- · 2019-01-24 00:14

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)

        })
查看更多
贼婆χ
5楼-- · 2019-01-24 00:26

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
查看更多
Juvenile、少年°
6楼-- · 2019-01-24 00:29

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
    }
}
查看更多
登录 后发表回答