DAY #41

Enum logic. You can clean up a lot of code by hiding logic in an enum.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
enum Genre {
    case fiction
    case scifi
    case nonFiction
    case history
    case science
    case medical
    case other(name: String) //Associated value

    var isSciencey: Bool {
        switch self {
            case .scifi, .science, .medical: return true
            default: return false
        }
    }
}
//The code above lets us do this:
let isSciencey = someGenre.isSciencey

//Instead of this:
let isSciencey = someGenre == .scifi || someGenre == .science || someGenre == .medical   

Originally published 09/26/2021 @ https://pittcsc.org/ Discord

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