我在使用扩展代码时遇到以下错误,我不确定他们是要求使用不同的运算符还是根据 Internet 搜索修改表达式中的值。
错误:% 不可用:改用 truncatingRemainder
扩展代码:
extension CMTime {
var durationText:String {
let totalSeconds = CMTimeGetSeconds(self)
let hours:Int = Int(totalSeconds / 3600)
let minutes:Int = Int(totalSeconds % 3600 / 60)
let seconds:Int = Int(totalSeconds % 60)
if hours > 0 {
return String(format: "%i:%02i:%02i", hours, minutes, seconds)
} else {
return String(format: "%02i:%02i", minutes, seconds)
}
}
}
设置分秒变量时出现错误。
最佳答案
CMTimeGetSeconds()
返回一个 float (Float64
又名
双
)。在 Swift 2 中你可以计算
浮点除法的余数为
let rem = 2.5 % 1.1
print(rem) // 0.3
在 Swift 3 中,这是通过
let rem = 2.5.truncatingRemainder(dividingBy: 1.1)
print(rem) // 0.3
应用于您的代码:
let totalSeconds = CMTimeGetSeconds(self)
let hours = Int(totalSeconds / 3600)
let minutes = Int((totalSeconds.truncatingRemainder(dividingBy: 3600)) / 60)
let seconds = Int(totalSeconds.truncatingRemainder(dividingBy: 60))
但是,在这种特殊情况下,转换持续时间更容易 首先是一个整数:
let totalSeconds = Int(CMTimeGetSeconds(self)) // Truncate to integer
// Or:
let totalSeconds = lrint(CMTimeGetSeconds(self)) // Round to nearest integer
然后下一行简化为
let hours = totalSeconds / 3600
let minutes = (totalSeconds % 3600) / 60
let seconds = totalSeconds % 60
关于ios - "% is unavailable: Use truncatingRemainder instead"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40495301/