为什么我不能更改 Timer.scheduledTimer 函数中变量的值?

Why I cannot change the value of variable inside Timer.scheduledTimer function?

当我尝试在 Timer 函数中更改 accumulatedTime 的值时,accumulatedTime 的值保持不变。

import UIKit

class WelcomeViewController: UIViewController {

    @IBOutlet weak var titleLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        titleLabel.text = ""
        var accumulatedTime = 0.0
        let logo = "Hello World"
        for letter in logo {
            Timer.scheduledTimer(withTimeInterval: accumulatedTime*0.1, repeats: false) { (timer) in
                self.titleLabel.text?.append(letter)
                accumulatedTime += 1  // increase the value of variable inside block function
            }
            print(accumulatedTime)
        }
    }
}

// Output is 0.0, 0.0, 0.0, 0.0, 0.0, 0.0...

但是如果我把"accumulatedTime += 1"移到Timer.scheduledTimer的block函数外面,accumulatedTime的值又可以改变了

import UIKit

class WelcomeViewController: UIViewController {

    @IBOutlet weak var titleLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        titleLabel.text = ""
        var accumulatedTime = 0.0
        let logo = "Hello World"
        for letter in logo {
            Timer.scheduledTimer(withTimeInterval: accumulatedTime*0.1, repeats: false) { (timer) in
                self.titleLabel.text?.append(letter)
            }
            accumulatedTime += 1 // increase the value of variable outside block function
            print(accumulatedTime)
        }
    }
}

// Output is 1.0, 2.0, 3.0, 4.0, 5.0...

我很好奇为什么我不能在Timer.scheduledTimer的块函数中更改局部变量的值,你们能帮我理解这里面的逻辑吗..谢谢

for letter in logo {
            Timer.scheduledTimer(withTimeInterval: accumulatedTime*0.1, repeats: false) { (timer) in
                self.titleLabel.text?.append(letter)
                accumulatedTime += 1  // increase the value of variable inside block function
            }
            print(accumulatedTime)
        }

打印语句在闭包执行之前运行...这就是为什么它们都是 0 ..因为当您的打印代码在 for 循环中执行时它不会被设置...在闭包中使用打印语句

for letter in logo {
                Timer.scheduledTimer(withTimeInterval: accumulatedTime*0.1, repeats: false) { (timer) in
                    self.titleLabel.text?.append(letter)
                    accumulatedTime += 1  // increase the value of variable inside block function
                    print(accumulatedTime)// print 1,2,3 .. 11
                }

            }

在 Closure 中它的值正在改变......你可以在闭包执行时访问改变的值..