Swift:将 UserDefaults 字典数据检索到标签中

Swift: Retrieving UserDefaults dictionary data into labels

我是 swift 编程新手。我将一些文本字段数据作为 UserDefaults 保存到字典中。我需要取回这些数据并按以下格式显示。

x 磅= x 磅 =x 克

这是我将其保存到字典中的 UserDefaults 中的代码。

 var weightDict = [String:Any]()
  var weightArray =  [Any]()

@IBAction func saveWeight(_ sender: Any) {


         weightDict = [:]
         weightDict.updateValue(textOunce.text, forKey: "ounce")
         weightDict.updateValue(textPound.text, forKey: "pound")
         weightDict.updateValue(textGram.text, forKey: "gram")
       weightArray.append(weightDict)


        let defaults = UserDefaults.standard

         defaults.set(weightArray,forKey: "savedWeightConversion")

        if let savedWeights = defaults.object(forKey: "savedWeightConversion"){
            weightArray = (savedWeights as! NSArray) as! [Any]
            print("value is",weightArray)
        }

    }

在应用程序加载时查看它

override func viewDidAppear(_ animated: Bool) {
        let defaults = UserDefaults.standard
    let savedWeights = defaults.object(forKey: "savedWeightConversion") as? [String] ?? [String]()


    }

你可以试试

  if let savedWeights = UserDefaults.standard.object(forKey: "savedWeightConversion") as? [Any] {

        if let dic  = savedWeights[0] as? [String:Any] {

            if let ounce  = dic["ounce"] as? String {

               self.ounceLb.text = ounce

            }

            if let pound  = dic["pound"] as? String {

                self.poundLb.text = pound

            }

            if let gram  = dic["gram"] as? String {

                self.gramLb.text = gram

            }

        }

    }

试试这个

override func viewWillAppear(_ animated: Bool) {
    if let savedWeights = UserDefaults.standard.object(forKey: "savedWeightConversion") as? [Any] {
        for i in 0 ..< savedWeights.count{
            if let weightDict  = savedWeights[i] as? [String:Any] {
                print("\(weightDict["pound"] as! String) pounds= \(weightDict["ounce"] as! String) ounds =\(weightDict["gram"] as! String) grams")
            }
        }
    }
}



@IBAction func saveWeight(_ sender: Any) {

    if let savedWeights = UserDefaults.standard.object(forKey: "savedWeightConversion") as? [Any] {
        weightArray = savedWeights
    }
    weightDict = [:]
    weightDict.updateValue(textOunce.text, forKey: "ounce")
    weightDict.updateValue(textPound.text, forKey: "pound")
    weightDict.updateValue(textGram.text, forKey: "gram")
    weightArray.append(weightDict)


    let defaults = UserDefaults.standard

    defaults.set(weightArray,forKey: "savedWeightConversion")

    if let savedWeights = UserDefaults.standard.object(forKey: "savedWeightConversion") as? [Any] {
        for i in 0 ..< savedWeights.count{
            if let weightDict  = savedWeights[i] as? [String:Any] {
                print("\(weightDict["pound"] as! String) pounds= \(weightDict["ounce"] as! String) ounds =\(weightDict["gram"] as! String) grams")
            }
        }
    }

}