I have the following code:
func foo() {
var sum = 0
var pendingElements = 10
for i in 0 ..< 10 {
proccessElementAsync(i) { value in
Hope this will help you.
func lock(obj: AnyObject, blk:() -> ()) {
objc_sync_enter(obj)
blk()
objc_sync_exit(obj)
}
var pendingElements = 10
func foo() {
var sum = 0
var pendingElements = 10
for i in 0 ..< 10 {
proccessElementAsync(i) { value in
lock(pendingElements) {
sum += value
pendingElements--
if pendingElements == 0 {
println(sum)
}
}
}
}
}
There is no native locking tools, but there are workarounds like explained in this SO question:
What is the Swift equivalent to Objective-C's "@synchronized"?
Using one of the answers, you can create a function:
func synchronize(lockObj: AnyObject!, closure: ()->()){
objc_sync_enter(lockObj)
closure()
objc_sync_exit(lockObj)
}
and then:
func foo() {
var sum = 0
var pendingElements = 10
for i in 0 ..< 10 {
processElementAsync(i) { value in
synchronize(pendingElements) {
sum += value
pendingElements--
if pendingElements == 0 {
println(sum)
}
}
}
}
}