In Swift enumerations, what’s the difference between raw values and associated values?
Answer Posted / iosraj
Raw values are used to associate constant (literal) values to enum cases. The value type is part of the enum type, and each enum case must specify a unique raw value (duplicate values are not allowed).
The following example shows an enum with raw values of type Int:
enum IntEnum : Int {
case ONE = 1
case TWO = 2
case THREE = 3
}
An enum value can be converted to its raw value by using the rawValue property:
var enumVar: IntEnum = IntEnum.TWO
var rawValue: Int = enumVar.rawValue
A raw value can be converted to an enum instance by using a dedicated initializer:
var enumVar: IntEnum? = IntEnum(rawValue: 1)
Associated values are used to associate arbitrary data to a specific enum case. Each enum case can have zero or more associated values, declared as a tuple in the case definition:
enum AssociatedEnum {
case EMPTY
case WITH_INT(value: Int)
case WITH_TUPLE(value: Int, text: String, data: [Float])
}
Whereas the type(s) associated to a case are part of the enum declaration, the associated value(s) are instance specific, meaning that an enum case can have different associated values for different enum instances.
| Is This Answer Correct ? | 2 Yes | 0 No |
Post New Answer View All Answers
How can we make a property optional in swift?
What is lazy stored procedure in swift and when is it used?
What are the most important features of swift?
What is the synonym of swift?
What is encapsulation in swift?
What are the different ways to pass data in swift?
What are methods in swift?
Is swift a good language?
What are the features of swift programming?
How do you make a swift bridging header?
What is singleton class swift 3?
Is it worth learning swift 2019?
What lazy stored properties is and when it is useful?
Do try catch swift?
What is floating point number in swift? What are the different floating point numbers in swift?