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


Please Help Members By Posting Answers For Below Questions

What is nil in swift?

442


Can enum be extended in swift?

458


What is difference between single and double, in swift?

486


What are the control transfer statements that are used in ios swift?

596


Is swift a functional language?

486






Is equal to string swift?

464


Why do we use swift? Mention some advantages of swift?

486


How many types of closures are there in swift?

421


Does apple use swift internally?

470


What is dynamic keyword in swift?

480


What is base class in swift?

434


What is indexpath in swift?

457


How to convert nsarray to nsmutablearray in swift?

631


How to make a method or variable generics in swift?

453


What is unowned in swift?

447