Created
September 2, 2019 06:04
-
-
Save muizidn/4b99ec98ab7fadbb79988e8a9a965a1d to your computer and use it in GitHub Desktop.
Encode and Decode to Data object in Swift 5.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol DataCodable { | |
func toData() -> Data | |
init(data: Data) | |
} | |
extension Data: DataCodable { | |
func toData() -> Data { | |
return self | |
} | |
init(data: Data) { | |
self = data | |
} | |
} | |
extension String: DataCodable { | |
func toData() -> Data { | |
guard let data = self.data(using: .utf8) else { | |
fatalError("Cannot encode using UTF8: \(self)") | |
} | |
return data | |
} | |
init(data: Data) { | |
self = String.init(data: data, encoding: .utf8)! | |
} | |
} | |
protocol NumericPrimitiveDataCodable: DataCodable { | |
associatedtype Primitive | |
} | |
extension NumericPrimitiveDataCodable where Self.Primitive == Self { | |
func toData() -> Data { | |
var value = self | |
return Data.init(bytes: &value, count: MemoryLayout<Primitive>.size) | |
} | |
init(data: Data) { | |
self = data.withUnsafeBytes { (bfr) -> Primitive in | |
return bfr.bindMemory(to: Primitive.self).first! | |
} | |
} | |
} | |
extension Int: NumericPrimitiveDataCodable { | |
typealias Primitive = Int | |
} | |
extension Double: NumericPrimitiveDataCodable { | |
typealias Primitive = Double | |
} | |
extension Bool: NumericPrimitiveDataCodable { | |
typealias Primitive = Bool | |
} | |
do { | |
print("Data Codable") | |
print(Bool.init(data: true.toData()) == true) | |
print(Double.init(data: Double.greatestFiniteMagnitude.toData()) == Double.greatestFiniteMagnitude) | |
print(Int.init(data: Int.max.toData()) == Int.max) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment