Pulling values out of an enum with associated value fields.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
// Lets take an old example
enum Genre {
case fiction
case scifi
case nonFiction
case history
case science
case medical
case other(name: String) //Associated value
}
// The defacto method for pulling out associated values invloves a switch statement
switch genre {
case .fiction:
//...
case .other(let name): print(name)
}
// However there is actually another method to pull out just the associated value
if case let .other(name) == "poetry" {
print(name)
}
//or
if case .other(let name) == "poetry" {
print(name
}
|
Originally published 09/24/2021 @ https://pittcsc.org/ Discord
Published here on 09/09/2022. Blog published date reflects the original date of publication.