简体   繁体   English

如何在viewDidLoad()Swift2中初始化变量

[英]How to initialize variable in viewDidLoad() Swift2

I am trying to create a stopWatch app as a part of learning swift. 我正在尝试创建一个秒表应用程序,作为快速学习的一部分。 Coming from Java I am having a hard time figuring out how to initialize a variable. 来自Java,我很难解决如何初始化变量。 Relevant code of viewcontroller: ViewController的相关代码:

var timerRunning = false

var timer: NSTimer = NSTimer() //first initialization I want to remove this initialization and leave it as nil


override func viewDidLoad() {
    super.viewDidLoad()
// second initialization
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.timeChanged), userInfo: nil, repeats: true)
}

func timeChanged(){
    print("1 second")
}

The problem I am facing is double initialization of the timer variable which I think is redundant and cannot set to nil. 我面临的问题是定时器变量的双重初始化,我认为这是多余的,无法将其设置为nil。 My goal is to use timer variable in a couple of functions and initialize it on a button pressed event. 我的目标是在几个函数中使用计时器变量,并在按钮按下事件时对其进行初始化。 The above approach works but I am looking for some cleaner/correct implementations. 上面的方法可行,但是我正在寻找一些更干净/正确的实现。 Thank You 谢谢

将您的计时器变量声明为可选变量,以使其最初具有nil值,之后您可以在按钮事件中实例化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM