SwiftUI preview with different @AppStorage values

I have SwiftUI views, which access the user defaults by using the property wrapper @AppStorage.

Now I would like to have a preview with multiple variations of the view depending on the same user default with different values. Is there a pure way to do that?

Currently I have a solution which is very probably a hack and supports only one variation of the user default. To do that I define the user settings in a sub views onAppear() method:

struct MyTestedView_Previews : PreviewProvider {
	static var previews: some View {
		VStack
		{
			VStack
			{
				MyTestedView
					.previewLayout(.sizeThatFits)
			}
			.onAppear{
				UserDefaults.standard.set(true, forKey: "myConsumedKey")
			}
			//VStack
			//{
			//	MyTestedView
			//	.previewLayout(.sizeThatFits)
			//}
			//.onAppear{
			//	UserDefaults.standard.set(false, forKey: "myConsumedKey")
			//}
		}
	}
}

When I have two VStack for different variations and I set the user defaults to different values in their onAppear(), only one user default value wins and I see one variation of my view twice.

What I also don't like on my solution, is that I don't know where this user default is stored. Is it stored temporary in the memory or do I even manipulate Xcode's user defaults?

Does anybody know if SwiftUI has already a solution to test different variations of user defaults in the preview?

Answered by Jackson-G in 796957022

Hey .. I'm using previews for different languages like this:

#Preview("English") {
    ContentView()
        .environment(\.locale, Locale(identifier: "EN"))
}

#Preview("Spanish") {
    ContentView()
        .environment(\.locale, Locale(identifier: "ES"))
}

It should work the same way for UserDefaults ;-)

Jackson

Hey .. I'm using previews for different languages like this:

#Preview("English") {
    ContentView()
        .environment(\.locale, Locale(identifier: "EN"))
}

#Preview("Spanish") {
    ContentView()
        .environment(\.locale, Locale(identifier: "ES"))
}

It should work the same way for UserDefaults ;-)

Jackson

@Jackson-G has provided an interesting answer.

But why do you want to do it in Preview and not in simulator. At the risk of pushing preview beyond its limits.

SwiftUI preview with different @AppStorage values
 
 
Q