What is '@AppStorage' in SwiftUI

ios dev·2022년 3월 19일
0

SwiftUI

목록 보기
1/1
post-thumbnail

@AppStorage

New in iOS 14

AppStorageUserDefaults에서 값을 읽기 위한 전용 propertyWrapper이다.
이 wrapper는 UserDefaults의 key를 감시하고 해당 key가 변경되면 UI를 새로 고친다.

Declaration

@frozen @propertyWrapper struct AppStorage<Value>

what is @frozen?
what is @propertyWrapper?


Parameters

public init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil)

wrappedValue

value가 정해지지 않으면 default value가 적용된다.

key

UserDefaults에서 값을 읽고 쓰기 위한 key

store

The user defaults store to read and write to. A value of nil will use the user default store from the environment.


Example

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

0개의 댓글