Search code examples
iosswiftxcode8nsuserdefaults

Storing more than one value of something using User Defaults


I am using xcode 8 swift 3. I have a mini App where I time myself how long I can answer the given questions, I have made it pass my time to the next VC and actually save it. I am wondering how do I save all the times I get in the App.

Button to save score

@IBAction func saveScore(_ sender: Any) {
    label.text = label.text
    UserDefaults.standard.set(label.text, forKey: "score")
}

User Defaults part

override func viewDidAppear(_ animated: Bool) {
    if let x = UserDefaults.standard.object(forKey: "score") as? String {   
        label.text = x
    }
 }

Solution

  • You can store Array of Dictionary to UserDefaults which contains more values

        let dict = ["score": "","userID":"1"] 
        let dict2 = ["score": "","userID":"2"] 
    
        let array = [dict,dict2]
        UserDefaults.standard.set(array, forKey: "scoreCard")
    

    And fetch like

    if let x = UserDefaults.standard.array(forKey: "scoreCard") as? [[String:Any]] {
      for  dict in x {
            //DO something 
            yourLabel.text = dict["score"] as! String
    
      }
    }
    

    Hope it is helpful to you