Getting data from array of dictionaries in an array

拈花ヽ惹草 提交于 2019-12-24 08:08:02

问题


I have created an Array of Dictionaries:

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

Now I have to create an array of Name only.

What I have done is this:

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

But is there any other efficient way of doing this.


回答1:


You can use flatMap (not map) for this, because flatMap can filter out nil values (case when dict doesn't have value for key "Name"), i.e. the names array will be defined as [String] instead of [String?]:

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



回答2:


Use compactMap as flatMap is deprecated.

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



来源:https://stackoverflow.com/questions/48637993/getting-data-from-array-of-dictionaries-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!