ios - "% is unavailable: Use truncatingRemainder instead"是什么意思?

标签 ios swift swift3 modulus

我在使用扩展代码时遇到以下错误,我不确定他们是要求使用不同的运算符还是根据 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/

相关文章:

swift - 从 url 异步加载 anchor 不起作用

ios - 如何用单个表格部分显示不同的 View ?

ios - 方向更改后 WKWebView 显示内容错误

ios - UITableView 背景颜色和分隔符样式更改不起作用

ios - 将 JSON 数据加载到 TableView 不起作用

json - 类型转换中的 Firebase Swift 3 错误

objective-c - applicationWillTerminate 不会在强制退出 iOS 应用程序时被调用

ios - 正确初始化 NSMutableString

ios - 如何从自定义 UICollectionViewCell 启动 View Controller

ios - KeyboardExtension adjustmentTextPosition 与表情符号有关的问题