RawValue
We can assign a value to each of the cases of an enum
. The most commonly used types for this are Int
and String
.
Let's see an example where we have an enum of type Int
. When we assign a value to the first case, the following cases will automatically get the next value in order, although we can assign any value to each case if we choose.
enum Planet: Int {
case mercury = 1
case venus
case earth
case mars
case jupiter
case saturn
case uranus
case neptune
}
print(Planet.mercury.rawValue) // 1
print(Planet.mars.rawValue) // 4
In the case of using an enum of type String
, we can also assign values. If we don't assign any, the name of the case
will be used as the value.
enum Planet: String {
case mercury = "Mercury"
case venus
case earth = "Earth"
case mars = "Mars"
case jupiter
case saturn = "Saturn"
case uranus = "Uranus"
case neptune = "Neptune"
}
print(Planet.mercury.rawValue) // Mercury
print(Planet.jupiter.rawValue) // jupiter
Not only can we retrieve the rawValue
of an enum, but we can also create them using Strings
or Ints
.
This init
returns an Optional
value, since it is possible that the provided value might not match any of the cases.
let myPlanet = Planet(rawValue: "Mars")
print(myPlanet) // Optional(Planet.mars)
let myPlanetTwo = Planet(rawValue: "venus")
print(myPlanetTwo) // Optional(Planet.venus)
let myPlanetFail = Planet(rawValue: "mars")
print(myPlanetFail) // nil
Enums and Decodable
You can add an enum
property to your Decodable
object. If the value on the JSON matches the RawValue
of the enum, it will be converted. To be able to do this, our enum should also adopt Decodable
protocol.
import Foundation
enum Planet: String, Decodable {
case mercury = "Mercury"
case venus = "Venus"
case earth = "Earth"
case mars = "Mars"
case jupiter = "Jupiter"
case saturn = "Saturn"
case uranus = "Uranus"
case neptune = "Neptune"
}
struct Person: Decodable {
let planet: Planet
}
let jsonString = """
{ "planet": "Earth" }
"""
if let data = jsonString.data(using: .utf8),
let me = try? JSONDecoder().decode(Person.self, from: data)
{
print(me)
}
Be the first to comment