使用扩展代码时,出现以下错误,我不确定他们是否要求使用其他运算符或基于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()
返回浮点数(Float64
akaDouble
)。在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/