问题
I have UserDefaults
array like:
let userValue = ["name": self.nameLbl.text ?? "", "lastName": self.lastNameLbl.text ?? "", "city": cityLbl.text ?? ""] as! [String : String]
var userArray = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] ?? []
userArray.append(userValue)
UserDefaults.standard.set(userArray, forKey: "userInfo")
How can I get key values example to print type
[["name": .., "lastName":..,],["name": .., "lastName":..,],["name": .., "lastName":..,]...]
If I print like this :
if let array = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] {
for dictionary in array {
print(dictionary["name"])
print(dictionary["lastName"])
print(dictionary["city"])
}
}
in console get :
Lars
James
Ulrich
Hetfield
Gentofte
California
I want it like this : [[ Lars, Ulrich,Gentofte],[James, Hetfield, California]]
回答1:
You have to add key-value
pair in the array and then print array. You will get your expected answer
let userValue = ["name": self.nameLbl.text ?? "", "lastName": self.lastNameLbl.text ?? "", "city": cityLbl.text ?? ""] as! [String : String]
var userArray = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] ?? []
// Appending the different -2 userValue to userArray
userArray.append(userValue)
userArray.append(userValue)
UserDefaults.standard.set(userArray, forKey: "userInfo")
if let array = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] {
var dataValues = Array<Any>()
array.forEach { (object) in
dataValues.append(Array(object.values))
}
print(dataValues)
}
Here you can check demo:
let userValue = ["name": "j", "lastName": "o", "city": "g"] as! [String : String]
// Appending the different -2 userValue to userArray
var a = [userValue, userValue, userValue]
var b = Array<Any>()
a.forEach { (object) in
b.append(Array(object.values))
}
print(b)
回答2:
To add an key-value
pair to existing array, you just to need to append userValue
to your array. Like:
let userValue = ["name": self.nameLbl.text ?? "", "lastName": self.lastNameLbl.text ?? "", "city": cityLbl.text ?? ""] as! [String : String]
var userArray = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] ?? []
// Append the userValue to userArray
userArray.append(userValue)
UserDefaults.standard.set(userArray, forKey: "userInfo")
To fetch the dictionary
from the array you can use
if let array = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] {
for dictionary in array {
print(dictionary["name"])
print(dictionary["lastName"])
print(dictionary["city"])
}
}
来源:https://stackoverflow.com/questions/50193212/swift-userdefaults-get-values-from-array