简体   繁体   English

Swift 中 userDidSetUp 的 UserDefaults 初始值

[英]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.导航 rootViewController 取决于用户设置,因为我曾尝试检查用户是否在主屏幕启动之前完成了所有入职表单。 My question is how to set inatial value to UserDefaults in my navigation.我的问题是如何在我的导航中将初始值设置为 UserDefaults。 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 { }方式是在代码中设置: 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.在控制台中打印true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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