Swift Language Protocols Using the RawRepresentable protocol (Extensible Enum)


// RawRepresentable has an associatedType RawValue.
// For this struct, we will make the compiler infer the type
// by implementing the rawValue variable with a type of String
// Compiler infers RawValue = String without needing typealias
struct NotificationName: RawRepresentable {
    let rawValue: String

    static let dataFinished = NotificationNames(rawValue: "DataFinishedNotification")

This struct can be extended elsewhere to add cases

extension NotificationName {
    static let documentationLaunched = NotificationNames(rawValue: "DocumentationLaunchedNotification")

And an interface can design around any RawRepresentable type or specifically your enum struct

func post(notification notification: NotificationName) -> Void {
    // use notification.rawValue

At call site, you can use dot syntax shorthand for the typesafe NotificationName

post(notification: .dataFinished)

Using generic RawRepresentable function

// RawRepresentable has an associate type, so the 
// method that wants to accept any type conforming to
// RawRepresentable needs to be generic
func observe<T: RawRepresentable>(object: T) -> Void {
    // object.rawValue