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

问题描述 投票:0回答:1

当我尝试在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的块函数之外,则可以再次更改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的块函数中更改局部变量的值,你们能帮助我了解其内部逻辑吗。谢谢

ios swift xcode iphone-developer-program
1个回答
0
投票
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
                }

            }

在闭包中,它的值正在更改...,并且在执行闭包时可以访问更改的值。

© www.soinside.com 2019 - 2024. All rights reserved.