I'm trying to follow this tutorial on iOS app development and I don't understand how or where rawValue gets defined in the 3rd last line in this statement
import SwiftUI
enum Theme: String {
case bubblegum
case buttercup
case indigo
case lavender
case magenta
case navy
case orange
case oxblood
case periwinkle
case poppy
case purple
case seafoam
case sky
case tan
case teal
case yellow
var accentColor: Color {
switch self {
case .bubblegum, .buttercup, .lavender, .orange, .periwinkle, .poppy, .seafoam,
.sky, .tan, .teal, .yellow: return .black
case .indigo, .magenta, .navy, .oxblood, .purple: return .white
}
}
var mainColor: Color {
Color(rawValue)
}
}
I understand that rawValue is a property of a case in an enumeration
so presumably rawValue
will point to some string associated with a case defined above.
But, how does is know which case we are using for mainColor
? The property doesn't refer to self
as in accentColor
.
Also, it appears that this is a calculated property with no setter, so it's not getting set at run time either (not that the argument is named anyways)
Is rawValue
defined somewhere in the import SwiftUI
? If so, why?
mainColor
is an instance computed property. self
is implied, but it can be explicitly stated. That is the code could say:
var mainColor: Color {
Color(self.rawValue)
}
Omitting self
is idiomatically common.
Just as in accentColor
, self
will be a particular case. That is, each case has a mainColor
and a corresponding accentColor
. There isn't a single mainColor
for Theme
.
In use you would say something like Theme.bubblegum.mainColor
.
The actual value of rawvalue
will be a String
equivalent to the case name - this is generated because the enum
declaration specifies a String
raw type but no explicit raw value is provided.