Skip to content

Instantly share code, notes, and snippets.

@muizidn
Created September 2, 2019 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muizidn/4b99ec98ab7fadbb79988e8a9a965a1d to your computer and use it in GitHub Desktop.
Save muizidn/4b99ec98ab7fadbb79988e8a9a965a1d to your computer and use it in GitHub Desktop.
Encode and Decode to Data object in Swift 5.0
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