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.
Error: % is unavailable: Use truncatingRemainder instead
Extension code:
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()
returns a floating point number (Float64
akaDouble
). In Swift 2 you could compute the remainder of a floating point division asIn Swift 3 this is done with
Applied to your code:
However, in this particular case it is easier to convert the duration to an integer in the first place:
Then the next lines simplify to
I found that the following works in Swift 3:
where
totalSeconds
is aTimeInterval
(Double
).Bring back the simple modulo syntax in swift 3:
This syntax was actually suggested on Apples official swift mailing list here but for some reason they opted for a less elegant syntax.
This simple swift 3 migration tip is part of a more comprehensive swift 3 migration guide with many insights (35k loc / 8-days of migration) http://eon.codes/blog/2017/01/12/swift-3-migration/
The
%
modulus operator is defined only for integer types. For floating-point types, you need to be more specific about the kind of IEEE 754 division/remainder behavior you want, so you have to call a method: eitherremainder
ortruncatingRemainder
. (If you're doing floating-point math you actually need to care about this, and lots of other stuff, or you can get unexpected / bad results.)If you actually intend to do integer modulus, you need to convert the return value of
CMTimeGetSeconds
to an integer before using%
. (Note that if you do, you'll lop off the fractional seconds... depending on where you're usingCMTime
that may be important. Do you want minutes:seconds:frames, for example?)Depending on how you want to present
CMTime
values in your UI, it might be better to extract the seconds value and pass it toNSDateFormatter
orNSDateComponentsFormatter
so you get appropriate locale support.