Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSNumber to NSTimeInterval in Swift

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.

like image 326
BeingShashi Avatar asked May 12 '15 15:05

BeingShashi


2 Answers

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))
like image 100
Blake Merryman Avatar answered Oct 01 '22 10:10

Blake Merryman


Try casting your NSNumber to a Double. This code works in a playground:

let aNumber: NSNumber = 1234567.89
let aDate = NSDate(timeIntervalSinceReferenceDate: Double(aNumber))
like image 26
Duncan C Avatar answered Oct 01 '22 10:10

Duncan C