Skip to content

Instantly share code, notes, and snippets.

@ajjames
Last active April 14, 2022 09:55
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ajjames/752ae68cd197db0aa8f64a609aba9c24 to your computer and use it in GitHub Desktop.
Save ajjames/752ae68cd197db0aa8f64a609aba9c24 to your computer and use it in GitHub Desktop.
Extendable 'enums' using RawRepresentable
import Foundation
/*
This is used by NSNotification.Name to allow enum-like members,
but where new members can be added in an extension!
enum Directions: String {
case north = "North"
}
extension Directions {
case south = "South" <-- This is not allowed by the compiler
}
*/
struct Direction: RawRepresentable {
typealias RawValue = String
var rawValue: String
init(_ rawValue: RawValue) {
self.rawValue = rawValue
}
init?(rawValue: RawValue) {
self.rawValue = rawValue
}
}
extension Direction {
static let North = Direction("North")
static let South = Direction("South")
}
extension Direction {
static let East = Direction("East")
static let West = Direction("West")
}
func display(_ value: Direction) {
print("\(value.rawValue)")
}
display(.West) // output: West
// The enum-like syntax above works because the parameter type contains a member of that type
// This can be leveraged as follows:
struct Thing {
let name: String
static let Thing1 = Thing(name: "Thing1")
static let Thing2 = Thing(name: "Thing2")
}
func display(_ value: Thing) {
print("\(value.name)")
}
display(.Thing1) // output: Thing1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment