使用 RawRepresentable 协议(可扩展枚举)

// 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")
}

此结构可以扩展到其他位置以添加案例

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

并且接口可以围绕任何 RawRepresentable 类型或特别是你的枚举结构进行设计

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

在呼叫站点,你可以使用点语法简写为类型安全 NotificationName

post(notification: .dataFinished)

使用通用的 RawRepresentable 函数

// 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
}