在swift 3中将[AnyObject]转换为[Int]

时间:2016-11-23 15:19:34

标签: arrays swift xcode int anyobject

我正在尝试在数字上创建一个数组,并让用户将它们保存在他们的设备上。但是,当保存数据时(通过使用NSUserDefaults方法),它将转换为[AnyObject]数组。我需要将其转换为[Int]数组。以下是我目前的做法:

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)
 }

我已经尝试了let weightData: Int = weighting as [Int],但它崩溃了,说是致命的错误 我已经尝试了print("\(weighting?[0] as! Int)"),但崩溃说Could not cast value of type '__NSCFArray' (0x109f6ae88) to 'NSNumber' (0x108df0300).

当我尝试

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

我的应用崩溃说Could not cast value of type '__NSCFArray' (0x108190e88) to 'NSNumber' (0x107016300)

有没有办法将保存的数组从[AnyObject]转换为[String][Int]

1 个答案:

答案 0 :(得分:0)

在第

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

您要保存[[Int]]类型的对象,因为chartData已经是数组。

删除括号

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