Skip to content

Instantly share code, notes, and snippets.

@jeffery812
Created April 10, 2019 07:46
Show Gist options
  • Save jeffery812/991aaa6f55cd1801205ce89cd4459100 to your computer and use it in GitHub Desktop.
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
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