I am still new to Swift and coding in general and I am trying to create some kind of option for the user to change colored themes.
But I am clueless on how to access a switch statement in a swift file (or how to encapsulate it) and how to access the set variable?
So far I let the user choose a theme in a settings view controller and the name of the theme is saved in UserDefaults in the key "theme".
In a file called themes.swift I have created a switch statement to check for the names. Each case can obviously set a couple of variables I have declared above the switch statement.
But I get the error that "Statements are not allowed at the top level"?
How can I fix this? And what can I do to let the switch statement run each time a view controller is presented to check for the correct colors or let it run once a new theme is selected and set the variables? I understand the error message but I have no idea on how to fix this.
For instance this is how I have set up the themes.swift file so far:
import UIKit
var theme = UserDefaults.standard.string(forKey: "themes")
var background: UIColor?
var labelColor: UIColor?
var buttonColor: UIColor?
switch theme {
case "Red":
background = UIColor(named: "darkRed")
labelColor = UIColor(named: "labelRed")
buttonColor = UIColor(named: "buttonRed")
case "Blue":
background = UIColor(named: "darkBlue")
labelColor = UIColor(named: "labelBlue")
buttonColor = UIColor(named: "buttonBlue")
default:
return
}
So how can I access those variables?
Besides the top level error, can I just access the variables like I would normally do because they are global variables?
Eg. startButton.setTitleColor(buttonColor, for: .normal)
?