Using the RawRepresentable protocol for an extensible enum
suggest change// RawRepresentable has an associated type, RawValue.
// The rawValue property lets the compiler infer RawValue = String
// without a typealias.
struct NotificationName: RawRepresentable {
let rawValue: String
static let dataFinished = NotificationName(rawValue: "DataFinishedNotification")
}
This struct can be extended elsewhere to add more values:
extension NotificationName {
static let documentationLaunched = NotificationName(rawValue: "DocumentationLaunchedNotification")
}
An interface can take this type, or any other RawRepresentable type:
func post(notification: NotificationName) -> Void {
// use notification.rawValue
}
At the call site, dot syntax names the value:
post(notification: .dataFinished)
A function that accepts any RawRepresentable type must be generic, because the protocol has an associated type:
func observe<T: RawRepresentable>(object: T) -> Void {
// object.rawValue
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents