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.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.