Search code examples
arraysswiftxcodeintanyobject

converting [AnyObject] to [Int] in swift 3


I am trying to create an array on numbers and have the user save them on their device. However when the data is saved (by using NSUserDefaults method) it is converted to an [AnyObject] array. I need to convert it to an array of [Int]. Here is my current approach to this:

class ProgressViewController: UIViewController {
  let kUserDefault = UserDefaults.standard
  var chartData = [Int]()
  override func viewWillAppear(_ animated: Bool) {
    let weighting = UserDefaults.standard.array(forKey: "chartData")
    footer1.text = "\((weighting))"
}
  @IBAction func AddGraphComponent(_ sender: UIButton) {
    var weighText:UITextField!
let alert = UIAlertController(title: "Enter new Weight!", message: "Please enter your Weight, followed by the date in which your weight was recorded", preferredStyle: UIAlertControllerStyle.alert)
alert.addTextField { (weighText) in
    weighText.placeholder = "Weight"
    weighText.keyboardType = UIKeyboardType.numberPad
}
alert.addTextField { (dateText) in
    dateText.placeholder = "Date (MM/YY)"
}
let confirmAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.default) { (_) in
    let field = alert.textFields![0] as? UITextField
    let weigh = alert.textFields![1] as? UITextField

        if (field?.text)! == "" || (weigh?.text)! == "" {
            let alert1 = UIAlertController(title: "Error!", message: "Please fill in BOTH fields", preferredStyle: UIAlertControllerStyle.alert)
            alert1.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert1, animated: true, completion: nil)
        }else {
            print((field?.text)!,(weigh?.text)!)
            let dataInt:Int = Int((field?.text!)!)!
            self.chartData.append(dataInt)
            self.chartLegend.append((weigh?.text)!)

            self.kUserDefault.set([self.chartData], forKey: "chartData") //as? [Int]
            self.kUserDefault.set([self.chartLegend], forKey: "chartLegend")
            self.kUserDefault.synchronize()
}
}
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
alert.addAction(confirmAction)
self.present(alert, animated: true, completion: nil)
 }

I've tried let weightData: Int = weighting as [Int] but it crashes saying fatal error I've tried print("\(weighting?[0] as! Int)") but it crashes saying Could not cast value of type '__NSCFArray' (0x109f6ae88) to 'NSNumber' (0x108df0300).

when I try

let weighting = UserDefaults.standard.array(forKey: "chartData") as! [Int]
print("\((weighting[0]))")

my app crashes saying Could not cast value of type '__NSCFArray' (0x108190e88) to 'NSNumber' (0x107016300)

is there any way to convert a saved array from [AnyObject] to [String] or [Int] ?


Solution

  • In the line

    self.kUserDefault.set([self.chartData], forKey: "chartData")
    

    you are saving an object of type [[Int]] since chartData is already an array.

    Remove the brackets

    self.kUserDefault.set(self.chartData, forKey: "chartData")