SwiftUI: AppStorage with Dynamic Key

Published by malhal on

If we want to use @AppStorage but with a dynamic key passed to the View we can do this:

DynamicKeyApp.swift

import SwiftUI

@main
struct DynamicKeyApp: App {
    
    var body: some Scene {
        WindowGroup {
            ContentView(counter: AppStorage(wrappedValue: 0, "counter"))
        }
    }
}

ContentView.swift

import SwiftUI

struct ContentView: View {
    @AppStorage<Int> var counter: Int
    
    var body: some View {
        VStack {
            Text("\(counter) Hello, world!")
            Button("Increment") {
                counter = counter + 1
            }
        }
        .padding()
    }
}
Categories: SwiftUI