Documentation.docc/AppPreferences/Getting Started.md
There are a few things to consider when using the Settings.
The Settings can be accessed from everywhere in the app like this:
@AppSettings(\.settingName)
var setting
Toggle("Enable some Feature", value: $setting)
When implementing a new feature, we might have some options in regards to this new feature we want to show the user in the apps Settings Window.
The settings window is structured in different sections. Figure out in which section your new option should appear in.
If the section is already populated with other options (e.g. Settings/GeneralSettings), just add your new option like this:
struct GeneralSettings: Codable, Hashable {
// ...
// This will be your new option. Be sure to provide a default value
public var yourNewOption: Bool = true
public init() {}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// ...
// Try to decode the value from json.
self.yourNewOption = try container.decodeIfPresent(
Bool.self,
forKey: .yourNewOption
) ?? true // If the key is not present in the json, set the default value
}
}
In some cases in early development the section you decided on where to put your option in might not yet have been implemented. In this
case you can create a new struct inside Settings like this:
public extension YourNewSection: Codable {
// This will be your new option. Be sure to provide a default value
public var yourNewOption: Bool = true
public init() {}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// Try to decode the value from json.
self.yourNewOption = try container.decodeIfPresent(
Bool.self,
forKey: .yourNewOption
) ?? true // If the key is not present in the json, set the default value
}
}
Now let's add the new section to Settings like this:
public struct Settings: Codable {
// ...
// Add your new section above the `public init() {}`
public var yourNewSection: YourNewSection = .init()
// ...
}
SettingsSettingsModel