从数组中的字典数组中获取数据

Getting data from array of dictionaries in an array

我创建了一个 ArrayDictionaries:

let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]

现在我只需要创建一个 Name 的数组。

我所做的是这样的:

var nameArray = [String]()
for dataDict in tempArray {
    nameArray.append(dataDict["Name"]!)
}

但是还有其他有效的方法吗?

您可以为此使用 flatMap(而不是 map),因为 flatMap 可以过滤掉 nil 值(当 dict 没有键值时"Name"),即 names 数组将被定义为 [String] 而不是 [String?]:

let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]
let names = tempArray.flatMap({ [=10=]["Name"] })
print(names) // ["ABC", "qwe", "rty", "uio"]

使用 compactMap 因为 flatMapdeprecated

let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]
let name = tempArray.compactMap({ [=10=]["Name"]})
print(name)