使用扩展代码时,出现以下错误,我不确定他们是否要求使用其他运算符或基于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()返回浮点数(Float64aka Double)。在Swift 2中,您可以将浮点除法的余数计算为
CMTimeGetSeconds()
Float64
Double
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