New in iOS 14
AppStorage는 UserDefaults에서 값을 읽기 위한 전용 propertyWrapper이다.
이 wrapper는 UserDefaults의 key를 감시하고 해당 key가 변경되면 UI를 새로 고친다.
Declaration
@frozen @propertyWrapper struct AppStorage<Value>
what is @frozen?
what is @propertyWrapper?
public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil)
value가 정해지지 않으면 default value가 적용된다.
UserDefaults에서 값을 읽고 쓰기 위한 key
The user defaults store to read and write to. A value of
nil
will use the user default store from the environment.
struct ContentView: View {
/// "Anonymous" 값은 프로그램이 "username" key를 찾지 못한 경우에 사용된다.
@AppStorage("username") var username: String = "Anonymous"
var body: some View {
VStack {
Text("Welcome, \(username)!")
Button("Log in") {
username = "@haanwave"
}
}
}
}
cf.
https://developer.apple.com/documentation/swiftui/appstorage
https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-appstorage-property-wrapper