Reputation: 157
I am new to swift programming. I am saving some text field data into a dictionary as UserDefaults. I need to retrieve these data back and display it in the following format.
x pounds= x ounds =x grams
This the code where I have saved it into UserDefaults in a dictionary.
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)
}
}
To view it on application load
override func viewDidAppear(_ animated: Bool) {
let defaults = UserDefaults.standard
let savedWeights = defaults.object(forKey: "savedWeightConversion") as? [String] ?? [String]()
}
Upvotes: 0
Views: 109
Reputation: 105
try this
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")
}
}
}
}
Upvotes: 1
Reputation: 100503
You can try
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
}
}
}
Upvotes: 1