UserDefaults inital value for userDidSetUp in Swift

70 Views Asked by At

Navigation rootViewController is dependent on user set up due to that I have tried to check if user did do all the onboarding forms before the main screen launch. My question is how to set inatial value to UserDefaults in my navigation. This always prints "false"

extension UserDefaults {
    var didUserSetUp: Bool? {
        get {
            ///// Register the app default:
            /// Initialize value from UserDefaults returns false
            UserDefaults.standard.register(defaults: ["didUserSetUp" : false])
            return UserDefaults.standard.bool(forKey: "didUserSetUp")
        }
        set {
            /// Set value to UserDefaults
            UserDefaults.standard.set(newValue, forKey: "didUserSetUp")
        }
    }

}

The way is set it in code: UserDefaults.standard.didUserSetUp = false if UserDefaults.standard.didUserSetUp { }

1

There are 1 best solutions below

1
On

You'd need to show example code of how you're attempting to use the property you've created, but I tried what you've shown here, and was able to get it working as expected. Here's what I did:

extension UserDefaults {
    var didCompleteOnboarding: Bool? {
        get {
            UserDefaults.standard.register(defaults: ["didCompleteOnboarding": false])
            return UserDefaults.standard.bool(forKey: "didCompleteOnboarding")
        }
        set {
            UserDefaults.standard.set(newValue, forKey: "didCompleteOnboarding")
        }
    }
}

Then in the root view controller:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        UserDefaults.standard.didCompleteOnboarding = true
        print(UserDefaults.standard.didCompleteOnboarding ?? false)
    }
}

Prints true in the console.