ran*_*dom 28 enumeration block objective-c nsarray swift
如何停止块枚举?
    myArray.enumerateObjectsUsingBlock( { object, index, stop in
        //how do I stop the enumeration in here??
    })
我知道你在obj-c中这样做:
    [myArray enumerateObjectsUsingBlock:^(id *myObject, NSUInteger idx, BOOL *stop) {
        *stop = YES;
    }];
Sam*_*fes 33
不幸的是,这改变了Swift的每个主要版本.这是一个细分:
斯威夫特1
stop.withUnsafePointer { p in p.memory = true }
斯威夫特2
stop.memory = true
斯威夫特3
stop.pointee = true
Chr*_*ich 23
在Swift 1中:
stop.withUnsafePointer { p in p.memory = true }
在Swift 2中:
stop.memory = true
在Swift 3-4中:
stop.pointee = true
hol*_*lex 20
从XCode6 Beta4开始,可以使用以下方法:
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)
        })
接受的答案是正确的,但仅适用于NSArrays.不适用于Swift数据类型Array.如果您愿意,可以使用扩展程序重新创建它.
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
            }
        }
    }
}
称之为
[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
    }
})
或者用于作为最后一个参数的块的功能
[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
    }
}
| 归档时间: | 
 | 
| 查看次数: | 8930 次 | 
| 最近记录: |