Raw values

Enumeration members can come prepopulated with default values (called raw values), which are all the same type. The following example presents an incomplete HttpErrorenum with raw values:

enum HttpError: Int { 
case badRequest = 400
case unauthorized = 401
case forbidden = 403
}

In the preceding example, the raw values for enum called HttpError are defined to be of the Int type and are set to some of their integer code.

Raw values can be of String, Character, Int, or any floating number types. Each raw value must be unique within its enumeration declaration.

Raw values are set to prepopulated values when we first define the enumeration such as HttpError in the preceding example; therefore, the raw value for an enumeration case is always the same and it is not going to change, unlike associated values.

If we define an enumeration with a raw-value type, the enumeration automatically receives an initializer that takes a value of the raw value's type and returns either an enumeration case or nil. We can use this initializer to try to create a new instance of the enumeration. The following example presents the initialization of an HttpError instance:

let possibleError = HttpError(rawValue: 400) 
print(possibleError?.rawValue ?? 404) // prints 400
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset