简体   繁体   中英

UserDefaults inital value for userDidSetUp in Swift

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 { }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM