如何打开剩余秒数以防止其为零



为什么我得到"展开可选值时意外发现nil?我检查了timerSeconds的值,它被正确地分配给了我想要的值。然而,当我调用函数StartTimer时,我的应用程序崩溃了。

300 EggTimer/ViewController.swift:30:致命错误:意外发现nil打开可选值2021-06-02 19:17:04.380375+1000EggTimer[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()
}
}

}

}

注意,在startTimer中,self.secondsRemaining与参数secondsRemaining:指的不是同一个东西

var secondsRemaining: Int? // self.secondsRemaining
@IBAction func hardnessSelected(_ sender: UIButton) {
...
}
func startTimer (secondsRemaining: Int?){ // you never use this parameter
//create a function called startTimer which accepts an interger as argument called secondsremaining
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
// here you are referring to the var declared outside of the methods
// which you never assign anything to.
// this does not refer to the parameter
if self.secondsRemaining! > 0 {

一个简单的解决方案是在startTimer:开始时将self.secondsRemaining设置为参数secondsRemaining

func startTimer (secondsRemaining: Int?){ // you never use this parameter
self.secondsRemaining = secondsRemaining
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
// same as before...

Hi@dumanji您还可以使用!强制展开两个常量!。如果您尝试使用一个为零的值,这可能会崩溃。特别是如果您计划将此应用程序推向生产,这可能会导致意外的运行时错误和应用程序崩溃。

示例:

  • let hardness=sender.currentTitle
  • 让timerSeconds=eggTimes[硬度]

考虑使用??(nil合并运算符(在常量右侧,以在可选返回nil的情况下提供默认值。

可能的方法:

  • 让timerSeconds=eggTimes[硬度]??420

如果这有帮助,请告诉我。

最新更新