使用 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
}