In Swift enumerations, what’s the difference between raw values and associated values?
In Swift enumerations, what’s the difference between raw values and associated values?
In Swift enumerations, raw values and associated values serve different purposes and have distinct characteristics.
Raw values are predefined constant values assigned to each case of an enumeration. These values are set at compile time and must be of the same type for all cases within the enumeration. The types that can be used for raw values include integers, strings, characters, or any other literal-convertible types. Raw values are useful when you need a fixed, identifiable value for each case, which can be used for comparison or serialization.
enum Direction: Int {
case north = 1
case south = 2
case east = 3
case west = 4
}
let direction = Direction.south
print(direction.rawValue) // Output: 2
In this example, each case of the Direction
enum is assigned a unique integer raw value.
Associated values, on the other hand, allow each case of an enumeration to store additional information of varying types. These values are specified when you create an instance of the enumeration and can differ for each case. Associated values make enums more flexible and capable of representing more complex data structures.
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
let productBarcode = Barcode.upc(8, 85909, 51226, 3)
let qrCode = Barcode.qrCode("ABCDEFGHIJKLMNOP")
In this example, the Barcode
enum has two cases: upc
with a tuple of four integers as its associated value, and qrCode
with a string as its associated value.
Type Consistency:
Initialization:
init?(rawValue:)
initializer, which returns an optional because the raw value might not match any case.Usage:
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào