ran*_*dom 28 enumeration block objective-c nsarray swift
如何停止块枚举?
myArray.enumerateObjectsUsingBlock( { object, index, stop in
//how do I stop the enumeration in here??
})
Run Code Online (Sandbox Code Playgroud)
我知道你在obj-c中这样做:
[myArray enumerateObjectsUsingBlock:^(id *myObject, NSUInteger idx, BOOL *stop) {
*stop = YES;
}];
Run Code Online (Sandbox Code Playgroud)
Sam*_*fes 33
不幸的是,这改变了Swift的每个主要版本.这是一个细分:
斯威夫特1
stop.withUnsafePointer { p in p.memory = true }
Run Code Online (Sandbox Code Playgroud)
斯威夫特2
stop.memory = true
Run Code Online (Sandbox Code Playgroud)
斯威夫特3
stop.pointee = true
Run Code Online (Sandbox Code Playgroud)
Chr*_*ich 23
在Swift 1中:
stop.withUnsafePointer { p in p.memory = true }
Run Code Online (Sandbox Code Playgroud)
在Swift 2中:
stop.memory = true
Run Code Online (Sandbox Code Playgroud)
在Swift 3-4中:
stop.pointee = true
Run Code Online (Sandbox Code Playgroud)
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)
})
Run Code Online (Sandbox Code Playgroud)
接受的答案是正确的,但仅适用于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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
称之为
[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
}
})
Run Code Online (Sandbox Code Playgroud)
或者用于作为最后一个参数的块的功能
[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
}
}
Run Code Online (Sandbox Code Playgroud)