问题
I have this delay function:
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
From here: dispatch_after - GCD in swift?
This code:
func start(){
for index in 1...3 {
delay(3.0){
println(index)
}
}
}
After 3 sec, it gives:
3
3
3
My Goal:
After 3 sec: 1
After 6 sec: 2
After 9 sec: 3
How whould I achieve this? Thank You,
回答1:
try multiplying delay with index
func start(){
for index in 1...3 {
delay(3.0 * index){
println(index)
}
}
}
回答2:
If you are (bizarrely) seeing 3 as the value of index that gets printed out on each of the iterations of the loop, you can do the following to ensure the correct (current) value of the iterator variable gets captured for the closure:
func start() {
for index in 1...3 {
let i = index
delay(3.0 * i) {
print(i)
}
}
}
I am not seeing that behaviour though with Xcode 7.3 & Swift 2.2 – the values printed are 1, 2, 3 with your version of the delay function. Are you perhaps using a very old version of Swift? This blog post actually covers the Swift for loop behaviour with value capture.
As noted in the other answer, multiplying the index with 3.0 accomplishes the 3,6,9 second delays.
回答3:
If you're looking for a more sophisticated approach, have a look at the types DelayManager
and LoopManager
here.
They enable straightforward loop syntax like this:
let loopId = LoopManager.shared.with(interval: 0.5, alternating: { [weak self] in
self?.alpha = 1
}, and: { [weak self] in
self?.alpha = 0.2
})
You can also cancel loops:
LoopManager.shared.stop(withUniqueId: loopId)
来源:https://stackoverflow.com/questions/36917544/swift-delay-in-loop