1

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
    }
 }
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571

1 Answers1

3

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

Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98
  • As there are multiple questions with each having its score. An array of dictionaries will be useful here with questionId and score. – Muhammad Zohaib Ehsan Sep 22 '17 at 05:32
  • UserDefault has a method called array(forKey:) exactly for retriving array values from UserDefaults – Leo Dabus Sep 22 '17 at 05:36
  • 1
    @MuhammadZohaibEhsan Edited answer – Prashant Tukadiya Sep 22 '17 at 05:36
  • 1
    @JonSnow Note that Swift native dictionary type for Swift 3+ is [String:Any] – Leo Dabus Sep 22 '17 at 05:40
  • 1
    Just remove the forced cast when setting it and cast the array to `[[String: Any]]` when retrieving it – Leo Dabus Sep 22 '17 at 05:45
  • 1
    @LeoDabus Fixed Please approve – Prashant Tukadiya Sep 22 '17 at 05:52
  • @JonSnow much better.. also if your dictionary only have string values change it to String:String which will make it easier to retrieve the dictionary strings – Leo Dabus Sep 22 '17 at 06:08
  • I am a bit confused i am sort of new to coding. So the array is holds the dict and dict 2. Then for the last bit of code it is storing it but i am not sure what to put it in the, for dict in x part. –  Sep 22 '17 at 10:23
  • @Seth `for dict in x` is a simple for each loop you will get each and every element of array in `dict` object you can print `dict` to check that :) – Prashant Tukadiya Sep 22 '17 at 10:57
  • @JonSnow i understand what you said. I've printed dict and it shows in my NSLog but i have tried printing it in a label it doesn't work. It says, cannot assign value of type [String: Any] with UILabel –  Sep 23 '17 at 08:09
  • @Seth Please approve answer if helpful to you – Prashant Tukadiya Sep 25 '17 at 10:01
  • 1
    @Jon Snow, sorry i didn't have internet for a while. Thanks for your help man it is very much appreciated! –  Sep 25 '17 at 10:41