gpt4 book ai didi

swift - slider 在 iPhone 上使程序崩溃,但在模拟器上运行

转载 作者:行者123 更新时间:2023-11-30 12:15:21 27 4
gpt4 key购买 nike

我使用此代码来跟踪和更新 slider 值,然后转换为字符串并显示在标签上。问题是,此代码在模拟器上有效,但在实际手机上崩溃了。出现错误“解包可选值时意外发现 nil”。我不知道是什么原因导致这种情况,任何帮助将不胜感激。

func updateSlider () {

    sliderBar.value = Float(CMTimeGetSeconds(self.audioPlayer.currentItem!.currentTime()))
let currentTime = Int((CMTimeGetSeconds(self.audioPlayer.currentItem!.currentTime())))
let duration = Int((CMTimeGetSeconds(self.audioPlayer.currentItem!.asset.duration)))
//let total = currentTime - duration

let minutes = currentTime/60
let seconds = currentTime - minutes * 60

let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60

self.lblPastTime.text = NSString(format: " %02d:%02d / %02d:%02d ",minutes2,seconds2, minutes,seconds) as String

}

最佳答案

避免强制展开变量是避免此类错误的好方法:

func updateSlider () {

guard let currentItem = self.audioPlayer.currentItem else { return }
sliderBar.value = Float(CMTimeGetSeconds(currentItem.currentTime()))
let currentTime = Int((CMTimeGetSeconds(currentItem.currentTime())))
let duration = Int((CMTimeGetSeconds(currentItem.asset.duration)))
//let total = currentTime - duration

let minutes = currentTime/60
let seconds = currentTime - minutes * 60

let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60

self.lblPastTime.text = NSString(format: " %02d:%02d / %02d:%02d ",minutes2,seconds2, minutes,seconds) as? String

}

使用 guard let 我安全地解开变量,因此如果它为 nil,函数就会返回。

关于swift - slider 在 iPhone 上使程序崩溃,但在模拟器上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45495832/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com