我正在寻找一种生成时间戳的Swifty方法。
我的macOS应用记录了一些数据,并在创建数据时标记了这些数据。然后,数据将通过网络发送(如Data),以在iPad上重建。
Data
是否有任何Swift类可用于生成时间戳?NSDate?NSTimeIntervalSince1970?CFAbsoluteTimeGetCurrent()
要求是:
Int
您可以Date将其转换为Data(8字节浮点数)并将其发送回Date如下:
Date
extension Numeric { var data: Data { var source = self return .init(bytes: &source, count: MemoryLayout<Self>.size) } init<D: DataProtocol>(_ data: D) { var value: Self = .zero let size = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)} ) assert(size == MemoryLayout.size(ofValue: value)) self = value } }
extension UInt64 { var bitPattern: Double { .init(bitPattern: self) } }
extension Date { var data: Data { timeIntervalSinceReferenceDate.bitPattern.littleEndian.data } init<D: DataProtocol>(data: D) { self.init(timeIntervalSinceReferenceDate: data.timeIntervalSinceReferenceDate) } }
extension DataProtocol { func value<N: Numeric>() -> N { .init(self) } var uint64: UInt64 { value() } var timeIntervalSinceReferenceDate: TimeInterval { uint64.littleEndian.bitPattern } var date: Date { .init(data: self) } }
游乐场测试
let date = Date() // "Nov 15, 2019 at 12:13 PM" let data = date.data // 8 bytes print(Array(data)) // "[25, 232, 158, 22, 124, 191, 193, 65]\n" let loadedDate = data.date // "Nov 15, 2019 at 12:13 PM" print(date == loadedDate) // "true"