Here is one way to implement @AppStorage using a custom UserDefaults suite by way of the defaultAppStorage View modifier and a class extension.

GroupDefaultsTestApp.swift

import SwiftUI

extension UserDefaults {
    static var group: UserDefaults {
        return UserDefaults(suiteName: "com.group.malcolmhall.shared")!
    }
}

@main
struct GroupDefaultsTestApp: App {
    
    var body: some Scene {
        WindowGroup {
            ContentView().defaultAppStorage(.group)
        }
    }
}

ContentView.swift

import SwiftUI

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

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().defaultAppStorage(.group)
    }
}
Categories: SwiftUI