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
In Swift, an enum cannot have both raw values and associated values at the same time.
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
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)