Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 为什么我不能在Timer.scheduledTimer函数中更改变量的值?_Ios_Swift_Xcode_Iphone Developer Program - Fatal编程技术网

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

Ios 为什么我不能在Timer.scheduledTimer函数中更改变量的值?,ios,swift,xcode,iphone-developer-program,Ios,Swift,Xcode,Iphone Developer Program,当我尝试在计时器功能内更改累计时间的值时,累计时间的值保持不变。 导入UIKit 类WelcomeViewController:UIViewController{ @IBVAR弱var标题标签:UILabel! 重写func viewDidLoad(){ super.viewDidLoad() titleLabel.text=“” var累计时间=0.0 让logo=“你好,世界” 用于标识中的字母{ Timer.scheduledTimer(时间间隔:累计时间*0.1,重复次数:false){

当我尝试在计时器功能内更改累计时间的值时,累计时间的值保持不变。

导入UIKit
类WelcomeViewController:UIViewController{
@IBVAR弱var标题标签:UILabel!
重写func viewDidLoad(){
super.viewDidLoad()
titleLabel.text=“”
var累计时间=0.0
让logo=“你好,世界”
用于标识中的字母{
Timer.scheduledTimer(时间间隔:累计时间*0.1,重复次数:false){(计时器)在
self.titleLabel.text?.append(字母)
累计时间+=1//增加块函数内变量的值
}
打印(累计时间)
}
}
}
//输出是0.0,0.0,0.0,0.0,0.0,0.0,0.0。。。
但是如果我将“累计时间+=1”移到Timer.scheduledTimer的block函数之外,则可以再次更改累计时间的值。

导入UIKit
类WelcomeViewController:UIViewController{
@IBVAR弱var标题标签:UILabel!
重写func viewDidLoad(){
super.viewDidLoad()
titleLabel.text=“”
var累计时间=0.0
让logo=“你好,世界”
用于标识中的字母{
Timer.scheduledTimer(时间间隔:累计时间*0.1,重复次数:false){(计时器)在
self.titleLabel.text?.append(字母)
}
累计时间+=1//增加块函数外部变量的值
打印(累计时间)
}
}
}
//输出是1.0,2.0,3.0,4.0,5.0。。。
我很好奇为什么我不能在Timer.scheduledTimer的block函数中更改局部变量的值,你们能帮我理解一下这里面的逻辑吗。。谢谢

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语句在闭包执行之前运行。。。这就是为什么他们都是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
                }

            }
最后,它的价值正在改变。。。执行闭包时,您可以访问更改的值