AppStorage property wrapper
@AppStorage
is a property wrapper in SwiftUI that allows you to read and write values to the user's defaults. It's a convenient way to store simple data types like strings, integers, booleans, etc., across app launches.
Looking at the example below.
@AppStorage("isSwitchOn") private var isSwitchOn: Bool = false
declares a property that is bound to the user's defaults. The key"isSwitchOn"
is used to identify the value in the defaults. If the value doesn't exist, it defaults tofalse
.- The
Toggle
view binds toisSwitchOn
, so when the toggle is switched on or off, the value in the user's defaults is updated accordingly. - The
Text
view displays the current state of the switch, which is also read from the user's defaults.
What can be stored in AppStorage?
Currently, you can store: Bool, Int, Double, String, URL, Data
Storing structs
You can also store structs that conform to codable
by converting it into Data type first and then store in AppStorage as a Data type.
you can put the encode and decode functions inside the struct for convenience but you can put them anywhere or even adapt them to maybe use generics.
Encoding -> Struct -> Data
Decoding -> Data -> Struct
struct UserAppStorage: Codable {
var name = ""
var age = 0
func encode() -> Data? {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(self) {
return encoded
} else {
return nil
}
}
static func decode(userData: Data) -> UserAppStorage? {
let decoder = JSONDecoder()
if let user = try? decoder.decode(UserAppStorage.self, from: userData) {
return user
} else {
return nil
}
}
}
as you can see @AppStorage
has a default value of a data. we call the encode function to get our struct to convert to data.
Alternative @AppStorage Initializers
It’s easy to see how using the initializers could be confusing and misleading to developers who are new to @AppStorage.
Developers are used to associating this kind of syntax when assigning a value to a variable. So it’s easy to think an @AppStorage key is being created and using this value.
Both of these initializers do the exact same thing.
@AppStorage("isToggleTrue") var isToggleTrue = false
// OR
@AppStorage(wrappedValue: false, "isToggleTrue") var isToggleTrue
The wrappedValue is the default value used if the isToggleTrue
key does not exist in app storage.
when to use:
- You want to store small amounts of data
- You want data to persist when the app closes
- You want to be able to bind directly to the values stored in @AppStorage