I have an enum
:
public enum PersonType:String {
case Cool = "cool"
case Nice = "rude"
case SoLazy = "so-lazy"
public var description: String {
switch self {
case .Cool:
return "Cool person"
case .Nice:
return "Nice person"
case .SoLazy:
return "its so lazy person"
}
}
public var typeImage: String {
switch self {
case .Cool:
return "cool.png"
case .Nice:
return "img_nice.png"
case .Solazy:
return "lazy.png"
}
}
}
The problem I don't know all the person type keys so I need to handle a default case of type person and to give it the description will be it's key like "so-lazy" and a default image.
let's say I get this result from the web service:
[
{
name: "john",
key: "cool"
},
{
name: "paul",
key: "funny"
}
]
I need to have a a default case to handle the key "funny"
here is how I init my enum while parsing and creating person object:
if let personType = PersonType(rawValue:personTypeKey ?? "") {
self.personType = personType
}
I want an else
or a better approach to handle the case of unknown keys in my enum, and give them the key as description and a default image.
The default value of an enumeration type E is the value produced by expression (E)0 , even if zero doesn't have the corresponding enum member.
Raw values are for when every case in the enumeration is represented by a compile-time-set value. The are akin to constants, i.e. So, A has a fixed raw value of 0 , B of 1 etc set at compile time. They all have to be the same type (the type of the raw value is for the whole enum, not each individual case).
Types in Swift fall into one of two categories: first, “value types”, where each instance keeps a unique copy of its data, usually defined as a struct, enum, or tuple. The second, “reference types”, where instances share a single copy of the data, and the type is usually defined as a class.
In Swift enum, we learned how to define a data type that has a fixed set of related values. However, sometimes we may want to attach additional information to enum values. These additional information attached to enum values are called associated values.
Another approach that works in Swift 3 (maybe 2, don't know):
enum PersonType: String {
case cool = "cool"
case nice = "nice"
case soLazy = "so-lazy"
case other
}
let person = PersonType(rawValue: "funny") ?? .other
The person variable is of type PersonType.other in this case.
The downside to this is that you don't know the raw string value of the .other case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With