Skip to content

Instantly share code, notes, and snippets.

@fonov
Last active December 9, 2022 14:29
Show Gist options
  • Save fonov/0ccf129ecc8252c6d30c133aa202a05b to your computer and use it in GitHub Desktop.
Save fonov/0ccf129ecc8252c6d30c133aa202a05b to your computer and use it in GitHub Desktop.
Demo of phantom types. Inspired by this article https://www.swiftbysundell.com/articles/phantom-types-in-swift/
// MARK: Phantom types
protocol Person {
var name: String { get set }
var position: String { get set }
func formatTitle() -> String
}
struct BasePerson<Character>: Person {
var name: String
var position: String
func formatTitle() -> String {
return "\(name) [\(position)]"
}
}
enum PersonCharacter {
enum Policeman {}
enum Doctor {}
enum Fireman {}
}
typealias Policeman = PersonCharacter.Policeman
typealias Doctor = PersonCharacter.Doctor
typealias Fireman = PersonCharacter.Fireman
let policeman = BasePerson<Policeman>(name: "Nik", position: "Officer")
let doctor = BasePerson<Doctor>(name: "Bob", position: "Surgeon")
let fireman = BasePerson<Fireman>(name: "Tom", position: "Operator fire engine")
extension BasePerson where Character == Policeman {
var policeDepartment: String {
"second devision"
}
var typeOfGun: String {
"pistol"
}
}
extension BasePerson where Character == Doctor {
var hospitalType: String {
"state hospital"
}
var doctorExperience: Int {
10
}
}
extension BasePerson where Character == Fireman {
var countOfFireEngines: Int {
10
}
var devision: [String] {
["main", "secondary", "backup"]
}
}
policeman.policeDepartment
policeman.formatTitle()
policeman.typeOfGun
doctor.doctorExperience
doctor.formatTitle()
doctor.hospitalType
fireman.countOfFireEngines
fireman.formatTitle()
fireman.devision
// MARK: End of phantom section
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment