Created
April 10, 2019 07:46
-
-
Save jeffery812/991aaa6f55cd1801205ce89cd4459100 to your computer and use it in GitHub Desktop.
https://www.swiftbysundell.com/posts/type-safe-identifiers-in-swift In "Identifying objects in Swift" we took a look at how objects can be identified using the built-in ObjectIdentifier type - and this week, we're going to construct similar identifi
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
struct Identifier: Hashable { | |
let string: String | |
} | |
extension Identifier: ExpressibleByStringLiteral { | |
init(stringLiteral value: String) { | |
string = value | |
} | |
} | |
extension Identifier: CustomStringConvertible { | |
var description: String { return string } | |
} | |
/* | |
Encode&Decode the string like this: | |
{ | |
"id": { | |
"string": "49-12-90-21" | |
}, | |
"name": "John" | |
} | |
*/ | |
extension Identifier: Codable { | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
string = try container.decode(String.self) | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
try container.encode(string) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment