TypedID
turns interchangeable IDs backed by common values types like String
into compiler differentiated, self-documenting, types like UserID
.
TypeID
doesn't affect how types are serialized. This means your IDs stay legible in logs — and you can use it in your app without changing endpoint definitions or migrating data already written out to your users's devices.
Add type-safety to your IDs in only three trivial lines of code.
- Add the SwiftPM dependency to your project:
.package(url: "https://github.com/adam-zethraeus/TypedID.git", from: "1.0.0")
- Import the library:
import TypeID
- Define your unique ID type:
struct UserID: TypedID {
let raw: String
}
Working with the resulting ID type is also trivial:
let myID = UserID("usr99999")
let otherID = UserID("usr11111")
// Equatabilty
let isSameUser = myID == otherID
// Hashability
let users = Set([myID, otherID])
// Codability
let encoded = try JSONEncoder().encode(myID)
let decoded = String(data: encoded, encoding: .utf8)
// TypedID is totally transparent. Serialized values remain the same.
assert(decoded == "usr99999")
TypeID
works with any ID type, including: String
, Int
, UUID
, UInt
, Double
, etc.
And if your existing ID's type isn't yet supported,implementing TypedID
's requirements for your type is just about equally trivial. (PRs are very welcome!)
...
That's it! Your IDs are now not only automatically distinguished from each other by the compiler, but also simply quicker and easier for humans to understand.