Setting UserDefaults in Preview

Hello, I've got a View that loads data from UserDefaults.

I want to set the value of the UserDefault in the preview so i can see how it looks while developing. However when i am trying to set it in preview, i get the following error when i try set it in preview.

'buildExpression' is unavailable: this expression does not conform to 'View'

What is the correct way to set the user defaults in preview?

import Foundation

class PreferencesViewModel: ObservableObject {
    @Published var maximumDistance: Double = UserDefaults.standard.value(for: .maximumDistance) as? Double ?? PreferencesViewModel.maximumDistanceOptions[0] {
        didSet {
            UserDefaults.standard.set(maximumDistance, for: .maximumDistance)
        }
    }

#Preview {
    let preferencesViewModel = PreferencesViewModel()
    preferencesViewModel.maximumDistance = 5.0
     PreferencesView()
        .environmentObject(PreferencesViewModel())
}
Answered by Developer Tools Engineer in 836750022

Hi @dwardu,

I believe what you have is not a valid ViewBuilder body. Adding a return statement in front of your PreferencesView() should resolve this error.

I think i solved my own issue, for those who need it in the future. I am using this solution in the PreferencesViewModel to ignore setting the user defaults

import Foundation

class PreferencesViewModel: ObservableObject {
    @Published var maximumDistance: Double = UserDefaults.standard.value(for: .maximumDistance) as? Double ?? PreferencesViewModel.maximumDistanceOptions[0] {
        didSet {
            //Check if running in preview mode
            #if DEBUG
            if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
                print("Preview mode detected. Not saving to UserDefaults.")
                return
            }
            #endif
            UserDefaults.standard.set(maximumDistance, for: .maximumDistance)
        }
    }
    ```


Hi @dwardu,

I believe what you have is not a valid ViewBuilder body. Adding a return statement in front of your PreferencesView() should resolve this error.

Setting UserDefaults in Preview
 
 
Q