How to stop enumerateObjectsUsingBlock Swift

亡梦爱人 提交于 2019-12-17 22:57:51

问题


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.



来源:https://stackoverflow.com/questions/24214136/how-to-stop-enumerateobjectsusingblock-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!