什么是“%不可用:改为使用truncatingRemainder”意思? [英] What does "% is unavailable: Use truncatingRemainder instead" mean?
问题描述
使用扩展代码时出现以下错误,我不确定他们是否要求使用其他运算符或根据互联网搜索修改表达式中的值。
I get the following error when using code for an extension, I'm not sure if they're asking to just use a different operator or modify the values in the expression based on an internet search.
错误:%不可用:改为使用truncatingRemainder
Error: % is unavailable: Use truncatingRemainder instead
分机代码:
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)
}
}
}
设置分钟和秒变量时会发生错误。
The error(s) occur when setting the minutes and seconds variables.
推荐答案
CMTimeGetSeconds()
返回一个浮点数( Float64
又名
Double
)。在Swift 2中,你可以计算浮点除法的
余数为
CMTimeGetSeconds()
returns a floating point number (Float64
aka
Double
). In Swift 2 you could compute the
remainder of a floating point division as
let rem = 2.5 % 1.1
print(rem) // 0.3
在Swift 3中,这是用
In Swift 3 this is done with
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))
但是,在这种特殊情况下,更容易转换持续时间
到第一位的整数:
However, in this particular case it is easier to convert the duration to an integer in the first place:
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
这篇关于什么是“%不可用:改为使用truncatingRemainder”意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!