ios - 如何解开剩余的秒数以防止它为零?
问题描述
为什么我在展开 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()
}
}
}
}
解决方案
请注意,在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 {
一个简单的解决方法是在开始时设置self.secondsRemaining
参数:secondsRemaining
startTimer
func startTimer (secondsRemaining: Int?){ // you never use this parameter
self.secondsRemaining = secondsRemaining
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
// same as before...
推荐阅读
- perl - 使用 Mojolicious::Plugin::SecureCORS 允许 CORS
- ios - 在 SceneKit iOS 中渲染流式视频的最有效方法是什么?
- java - 如何将 Java Hashmap Hierarchy 转换为 Redis Cache 中的等价物?
- java - 邮递员返回 404 以获取其余 API
- dart - 向 Dart 添加对 navigator.mediaDevices.getUserMedia 的支持
- python - 如何使用带有子图的 pandas 绘图。ax=df.plot() 或 df.plot(ax=ax1)。有什么不同
- delphi - 德尔福网页浏览
- r - 使用 httr 解决“SSL 证书问题:无法获取本地颁发者证书”
- raku - raku 中角色的签名限制
- html - HTML/CSS 导航菜单:桌面侧;手机全屏