Last active
August 28, 2024 14:09
-
-
Save ajjames/752ae68cd197db0aa8f64a609aba9c24 to your computer and use it in GitHub Desktop.
Extendable 'enums' using RawRepresentable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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