您可以
Date将其转换为
Data(8字节浮点数)并将其发送回
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:extension UInt64 { var bitPattern: Double { .init(bitPattern: self) }})} ) assert(size == MemoryLayout.size(ofValue: value)) self = value }}
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 bytesprint(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"
游乐场测试
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)