Date.copy() in Swift 3.0
Asked Answered
F

1

7

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

Flavopurpurin answered 23/1, 2017 at 11:1 Comment(0)
F
15

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
Flavopurpurin answered 23/1, 2017 at 11:1 Comment(1)
Your answer is correct - but if you were perverse, you could also say let newDate = ((oldDate as NSDate).copy()) as! Date :)Jerboa

© 2022 - 2024 — McMap. All rights reserved.