BeingShashi
BeingShashi

Reputation: 159

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.

Upvotes: 9

Views: 16964

Answers (2)

Blake Merryman
Blake Merryman

Reputation: 4105

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))

Upvotes: 32

Duncan C
Duncan C

Reputation: 131491

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

let aNumber: NSNumber = 1234567.89
let aDate = NSDate(timeIntervalSinceReferenceDate: Double(aNumber))

Upvotes: 5

Related Questions