DAY #8

Enums are really powerful!

Associated values: You can store custom values in an enum.

1
2
3
4
5
6
7
8
9
enum Genre {
    case fiction
    case scifi
    case nonFiction
    case history
    case science
    case medical
    case other(name: String) <———
}

Raw values: You can store raw values in an enum. This can be especially useful if you are trying to wrap a reference type like a String (see below) in a value type (enum).

1
2
3
4
5
6
7
enum Routes: String {
    case home = /home
    case about = /about
    case library = /library
    case contact = /contact
}
let homePath: URL = URL(www.you.com + Routes.home.rawValue)

There is so much more (recursive enums, putting methods inside enums, unwrapping enums, ..)! Enums can be used for so much more than just “options”. One cool thing I’ve seen enums used for before is controlling a C state machine.

Originally published 04/10/2021 @ https://pittcsc.org/ Discord

Published here on 09/08/2022. Blog published date reflects the original date of publication.