Search code examples
swiftuiswitch

my UIswitch value is nil even when its on I have to turn swich off and then back on for it to set value


using UIswitch to set value my variable is static because im using them in diffrent swift file so when I run program and click registration button it prints nil even tho its on (button stays the way it was left when closing app) I have to toggle it and then click registration button for it to print optional(true) what can i do so user dont have to togggle everytime they open app or when it shows on when app opened but value is nil also I just want it to print true/false (how do i unwrap)

class FirstViewController: UIViewController, UITextFieldDelegate {
    static var FirstColor: Bool!

    @IBAction func home(_ sender: RoundButton) {
    }
    @IBAction func Registration(_ sender: RoundButton) {
        print(FirstViewController.FirstColor)
    }

    @IBAction func ColorSwitch(_ sender: UISwitch) {
        if sender.isOn{
            FirstViewController.FirstColor = true
        }else{FirstViewController.FirstColor = false }
    }
}

Solution

  • If you want to persist the switch status you need to store it in UserDefaults. Don't add a static property in FirstViewController. Create a separate class like this with a computed property

    class Color {
        static var firstColor: Bool {
            get { return UserDefaults.standard.bool(forKey: "firstColor") }
            set { UserDefaults.standard.set(newValue, forKey: "firstColor") }
        }
    }
    

    In FirstViewController's viewDidLoad get last status and update

    override func viewDidLoad() {
        super.viewDidLoad()
        mySwitch.isOn = Color.firstColor
    }
    

    In Switch's action change it

    @IBAction func ColorSwitch(_ sender: UISwitch) {
        sender.isOn = !sender.isOn
        Color.firstColor = sender.isOn
    }