Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date.copy() in Swift 3.0

Since the switch to Swift 3.0, and along with it the change of NSDate to Date, the class no longer conforms to the NSCopying protocol.

In Swift 2, this was valid:

let newDate = oldDate.copy()

But now returns a compiler error.

With this being the case, what is the best way to duplicate a Date object?

let newDate = Date(timeIntervalSince1970: oldDate.timeIntervalSince1970)

This will do the trick, but it doesn't seem particularly elegant. And it is potentially (theoretically) susceptible to loss of precision as a TimeInterval is a Double (and we have no way of confirming that a Date object internals uses - or always will use - a Double).

like image 414
JoGoFo Avatar asked Jan 23 '17 11:01

JoGoFo


1 Answers

Answering my own question as I figured it out before I finished typing it. Hopefully it will help someone else.

Date in Swift 3 is now a struct, not a class. Which is a value type. Which means that it does not need to be 'copied', simply assigning it to a new variable will copy the data:

let newDate = oldDate
like image 94
JoGoFo Avatar answered Sep 20 '22 13:09

JoGoFo