如何停止块枚举?
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;
}];
答案 0 :(得分:33)
不幸的是,这改变了Swift的每个主要版本。这是一个细分:
Swift 1
stop.withUnsafePointer { p in p.memory = true }
Swift 2
stop.memory = true
Swift 3
stop.pointee = true
答案 1 :(得分:20)
在Swift 1中:
stop.withUnsafePointer { p in p.memory = true }
在Swift 2中:
stop.memory = true
在Swift 3 - 4中:
stop.pointee = true
答案 2 :(得分: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)
})
答案 3 :(得分:6)
接受的答案是正确的,但仅适用于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
}
}
答案 4 :(得分:-3)
只需stop = true
由于stop被声明为inout,swift将负责为你映射间接。