Search code examples
iosswiftnsuserdefaults

How to multiply a userDefault by a number?


how would I be able to multiply a user default by a number

my app crashes when I try to multiply my user default by a number in my FeesVC

It works perfectly fine passing the subtotal to the subtotalLbl (when by itself) but crashes the app if I try to multiply by any number with the UserDefault when trying to calculate for the salesTaxLbl and overallTotalLbl

class FooterCell: UITableViewCell {

    @IBOutlet weak var cartTotal: UILabel!
    @IBOutlet weak var totalInfoBtn: UIButton!

    @IBAction func additionalFeesOnClicked(_ sender: Any) {
        UserDefaults.standard.set(cartTotal.text, forKey: "PASS_DATA")
    }
}

class FeesViewController: UIViewController {

    @IBOutlet weak var subtotalLbl: UILabel!
    @IBOutlet weak var salesTaxLbl: UILabel!
    @IBOutlet weak var overallTotalLbl: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // passes data into FeesVC Fine
        let subtotal = UserDefaults.standard.object(forKey: "PASS_DATA") 

        // app crashed when trying to multiply the user default by a number
        let tax = Float(subtotal)! * Float(0.0825) 
        let total = Float(subtotal)! + Float(tax) 

        subtotalLbl.text = "\(subtotal!)"
        salesTaxLbl.text = "\(Tax)"
        overallTotalLbl.text = "\(total)"

    }

    @IBAction func returnButton(_ sender: Any) {
        dismiss(animated: true, completion: nil)
        print("Close Taxes and Fees")
    }   
}

Solution

  • When working with values in UserDefaults like this, it can often be helpful to wrap them up with a custom get & set in a variable so that you may access them like normal variables.

    var subTotal: Float {
        get {
            return UserDefaults.standard.float(forKey: "PASS_DATA")
        }
        set {
            UserDefaults.standard.set(newValue, forKey: "PASS_DATA")
        }
    }
    

    This would give you a variable that performs like a normal Float, so you can operate on it without having to concern yourself about the implementation details.

    Now, you can do this and everything Just Works (tm).

    let tax = subtotal * Float(0.0825)
    

    Updated to show this in action.

    When a breakpoint is hit, I run the po UserDefaults.standard.float(forKey: "PASS_DATA") command in the right side of the bottom console. This allows you to query values.

    When no value has been set for PASS_DATA, then you will get the default value of 0.0 as seen here:

    enter image description here

    However, if a value has been set, then you will see it as seen here where I set 5.0 before I print it out.

    enter image description here