Skip to content

bpisano/Phantom

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PhantomType

A Swift package to easily create phantom types for enhanced type safety.

Table of Contents

Installation

Add the following dependency to your Package.swift file:

dependencies: [
    .package(url: "https://github.com/bpisano/phantom", .upToNextMajor(from: "1.0.0"))
]

Usage

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)

Accessing values

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 value

Custom typealias name

By 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)

License

PhantomType is available under the MIT license. See the LICENSE file for more info.

About

Phantom type safety, without boilerplate.

Topics

Resources

License

Stars

Watchers

Forks

Languages