Swift UserDefaults从数组中获取值

时间:2018-05-05 19:21:44

标签: arrays swift nsuserdefaults

我有UserDefaults数组,如:

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

如何获取打印类型的键值示例

[["name": .., "lastName":..,],["name": .., "lastName":..,],["name": .., "lastName":..,]...]

如果我这样打印:

if let array = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] {
    for dictionary in array {
        print(dictionary["name"])
        print(dictionary["lastName"])
        print(dictionary["city"])
    }
}

在控制台获取:

Lars James Ulrich Hetfield Gentofte California

我想要这样:[[ Lars, Ulrich,Gentofte],[James, Hetfield, California]]

2 个答案:

答案 0 :(得分:1)

您必须在数组中添加key-value对,然后打印数组。你会得到你期望的答案

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)

 }

您可以在此处查看演示:

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)

答案 1 :(得分:0)

要向现有阵列添加key-value对,您只需将userValue附加到阵列即可。像:

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

要从数组中获取dictionary,您可以使用

    if let array = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] {
        for dictionary in array {
            print(dictionary["name"])
            print(dictionary["lastName"])
            print(dictionary["city"])
        }
    }