Alex
Alex

Reputation: 5119

Simple math operations in Swift not working as they should

Alright, let's imagine I have an NSDate object date, that is in the past, and I want to calculate the number of seconds that have passed. This is how I do it:

let timeInterval = -date.timeIntervalSinceNow

Then I want to decompose that into minutes, seconds and centi-seconds:

let seconds = Int(timeInterval) % 60
let minutes = Int(timeInterval - seconds) / 60
let centiSeconds = Int((timeInterval - Int(timeInterval)) * 100)

Except that the compiler complains about the last two lines, and I cannot figure out why.

For the minutes line it says Could not find and overload for '/' that accepts the supplied arguments, and for the centiSeconds line it says Could not find and overload for 'init' that accepts the supplied arguments. What am I doing wrong? Isn't this acceptable in Swift-land?

Upvotes: 0

Views: 1126

Answers (1)

ColinE
ColinE

Reputation: 70122

It's all a matter of where you apply the cast:

let timeInterval = -now.timeIntervalSinceNow

let seconds = Int(timeInterval) % 60
let minutes = (Int(timeInterval) - seconds) / 60
let centiSeconds = timeInterval - floor(timeInterval)) * 100

The underlying issue is that now.timeIntervalSinceNow returns an NSTimeInterval which is a floating point. As a result, the following is a compilation error:

let minutes = Int(timeInterval - seconds) / 60

However, the error Xcode reports Could not find and overload for 'init' that accepts the supplied arguments is incorrect and is not the root cause here.

Upvotes: 3

Related Questions