Difference between associated and raw values in swift enumerations

后端 未结 3 1845
我寻月下人不归
我寻月下人不归 2021-02-12 22:35

Swift enumerations have both associated and raw values. But the use cases of these values is not clear to me. So I would really appreciate if anyone can explain the difference b

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-12 23:26

    In Swift, an enum cannot have both raw values and associated values at the same time.

    Raw Values

    enum Color: String {
        case white = "#ffffff"
        case black = "#000000"
    }
    

    A "raw value" is an unique identifier of a type. It means that you are able to construct your type by ID. For example:

    XCTAssertEqual(Color.white, Color(rawValue: "#ffffff"))
    

    To get raw value use

    Color.white.rawValue
    

    Associated Values

    enum Color {
        case white
        case black
        
        case custom(hex: String)
    }
    

    Swift's "associated values" allows you to add additional information into enum that can be defined dynamically. Please note when we introduce "associated values", we omit the "raw values" and add a type annotation. This makes it impossible to use the "raw value" to reconstruct your type, because it is now set up dynamically.

    You can read the "associated value" as follows:

    let myColor = Color.custom(hex: "#ff00ff")
        
    switch myColor {
    case .custom(let hex):
        print("custom color hex:\(hex)") //#ff00ff
    case .white:
        print("white color")
    case .black:
        print("black color")
    }
    

    Please note that Objective-C does not support Swift's enum(except Int-bound)

提交回复
热议问题