简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM