Convert NSNumber to NSTimeInterval in Swift

BeingShashi picture BeingShashi · May 12, 2015 · Viewed 15.4k times · Source

I'm stuck with some sort of casting in Swift as I am very new to Swift.

Here is my code:

 if let matchDateTime = item["matchDate"].number {
     _matchDateTime=matchDateTime
 }

 println(_matchDateTime)                      
 let date = NSDate(timeIntervalSince1970:_matchDateTime)

but its giving me the error:

Extra argument timeSinceInterval1970 in call

I don't know whats that error, may be convert NSNumber to NSTimeInterval but how? No idea.

Anyone who can help me out with this.

Thanks in advance.

Answer

Blake Merryman picture Blake Merryman · May 12, 2015

NSTimeInterval is just a typedaliased Double.

Therefore casting from NSNumber to NSTimeInterval:

let myDouble = NSNumber(double: 1.0)
let myTimeInterval = NSTimeInterval(myDouble.doubleValue)

Edit: And the reverse is true.

let myTimeInterval = NSTimeInterval(1.0)
let myDouble = NSNumber(double: myTimeInterval)

Edit 2: As @DuncanC points out in the comments below, you can cast directly in the method call:

let date = NSDate(timeIntervalSince1970: NSTimeInterval(_matchDateTime))