A Swift package to easily create phantom types for enhanced type safety.
Add the following dependency to your Package.swift file:
dependencies: [
.package(url: "https://github.com/bpisano/phantom", .upToNextMajor(from: "1.0.0"))
]Add the @Phantom macro to your struct and mark the property you want to use as the identifier with @PhantomProperty.
import PhantomType
@Phantom
struct Person {
@PhantomProperty
var id: UUID
}The @Phantom macro will expand to the following:
struct Person {
typealias Id = PhantomType<UUID, Person>
@PhantomWrapped<UUID, Person>
var id: UUID
}This allows you to initialize the struct as usual, while also generating a phantom type for the specified property for enhanced type safety.
// Improved type safety
func registerPerson(withId id: Person.Id) { }
// Initialize a Person with a regular UUID, not the phantom type
let person: Person = .init(id: UUID())
registerPerson(withId: person.$id)You can access both the phantom type and the raw value using the generated properties.
let person: Person = .init(id: UUID())
print("Person ID: \(person.$id)") // Access the phantom type
print("Raw ID: \(person.id)") // Access the raw valueBy default, the typealias name is derived from the property name. You can optionally specify a custom name for the generated typealias:
import PhantomType
@Phantom
struct Person {
@PhantomProperty("PersonID")
var id: UUID
}
// Generates: typealias PersonID = PhantomType<UUID, Person>
let person: Person = .init(id: UUID())
func register(personId: Person.PersonID) {
// Implementation
}
register(personId: person.$id)PhantomType is available under the MIT license. See the LICENSE file for more info.