Convert NSNumber to NSTimeInterval in Swift
Asked Answered
I

2

9

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.

Impartible answered 12/5, 2015 at 15:49 Comment(2)
You need to click the check mark to accept one of the correct answers you've been given. Up-voting is entirely optional, but by asking a question you are expected to accept the best answer given if it answers the question. Failing to accept a correct answer is considered rude on SO.Phonoscope
You need to accept one of the answer you have been given, or explain how they don't solve your problem. Failure to accept a correct answer is considered very bad form on SO.Phonoscope
S
32

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))
Soupy answered 12/5, 2015 at 16:10 Comment(3)
Swift is nicer about casting between NSNumber and scalar number types than Objective-C is, so you can also use the syntax Double(myDouble) or NSTimeInterval(myDouble) where myDouble is an NSNumber like in your answer.Phonoscope
That's great that Swift handles that in a nicer way. I still prefer the above method as it is cleaner (IMO) and less likely to break with a new version of Swift (as it uses the established Cocoa API for NSNumber).Soupy
Fair enough. I prefer the Swift style when working in Swift. Personal taste, I suppose. (And I think that changes to a core feature like type casting are exceedingly unlikely. That part of the language is well defined.)Phonoscope
P
5

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

let aNumber: NSNumber = 1234567.89
let aDate = NSDate(timeIntervalSinceReferenceDate: Double(aNumber))
Phonoscope answered 12/5, 2015 at 16:8 Comment(1)
You should accept either my or Blake's answer. Both solve your problem. Pick the one you're more comfortable with.Phonoscope

© 2022 - 2024 — McMap. All rights reserved.