为什么我在展开 Optional 值时得到“意外发现 nil?我检查了 timerSeconds 的值,它被正确地分配给了我想要分配的值。但是,当我调用函数 StartTimer 时,我的应用程序崩溃了。
300 EggTimer/ViewController.swift:30: 致命错误:在展开可选值时意外发现 nil 2021-06-02 19:17:04.380375+1000 EggTimer[27674:932041] EggTimer/ViewController.swift:30: 致命错误:意外在展开可选值 (lldb) 时发现 nil
import UIKit
class ViewController: UIViewController {
let eggTimes : [String : Int] = ["Soft": 300, "Medium": 420, "Hard": 720]
var secondsRemaining: Int?
@IBAction func hardnessSelected(_ sender: UIButton) {
let hardness = sender.currentTitle!
let timerSeconds = eggTimes[hardness]!
print(timerSeconds)
//until here the code seems to work fine
startTimer(secondsRemaining: timerSeconds)
//call the function start timer and give the secondRemaining argument the value of timerSeconds
}
func startTimer (secondsRemaining: Int?){
//create a function called startTimer which accepts an interger as argument called secondsremaining
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
if self.secondsRemaining! > 0 {
//if the secondsRemaining >
print ("\(self.secondsRemaining ?? 0) seconds")
self.secondsRemaining! -= 1
}else {
Timer.invalidate()
}
}
}
}