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.

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
BeingShashi
  • 159
  • 1
  • 3
  • 11
  • 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. – Duncan C Apr 07 '16 at 10:53
  • 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. – Duncan C Jun 07 '16 at 13:21

2 Answers2

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))
Blake Merryman
  • 4,005
  • 1
  • 16
  • 14
  • 1
    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. – Duncan C May 12 '15 at 17:10
  • 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). – Blake Merryman May 12 '15 at 17:21
  • 1
    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.) – Duncan C May 12 '15 at 17:56
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))
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • 2
    You should accept either my or Blake's answer. Both solve your problem. Pick the one you're more comfortable with. – Duncan C May 12 '15 at 18:46