什么是“% 不可用:使用 truncatingRemainder 代替"?意思是? [英] What does "% is unavailable: Use truncatingRemainder instead" mean?

查看:23
本文介绍了什么是“% 不可用:使用 truncatingRemainder 代替"?意思是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用扩展代码时遇到以下错误,我不确定他们是要求使用不同的运算符还是根据 Internet 搜索修改表达式中的值.

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 aka).在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆