[英]How to write a dynamodb query in swift to fetch all values with a particular partition key
[英]Fetch all values for a particular key from a Dictionary in Swift
我有一個這樣的字典數組。
let arr = [["EmpName" : "Alex", "Designation" : "Jr. Developer"],
["EmpName" : "Bob", "Designation" : "Sr. Developer"],
["EmpName" : "Claire", "Designation" : "Jr. Developer"],
["EmpName" : "David", "Designation" : "Project Manager"]]
現在我想從中獲取EmpName
對象。 我如何在swift中執行此操作? 我基本上想要一個具有以下值的數組。
["Alex", "Bob", "Claire", "David"]
這就是我現在所做的。 但我想知道我是否可以通過使用filter
或map
來做到這一點......
var employees = [String]()
for empRecord in arr {
employees.append(empRecord["EmpName"]!)
}
一種簡單的方法是使用flatMap
:
let employees = arr.flatMap { $0["EmpName"] }
結果:
[“亞歷克斯”,“鮑勃”,“克萊爾”,“大衛”]
Swift中的flatMap
就像map
但它也安全地展開了optionals,這是我們需要的,因為Swift詞典總是返回Optionals。
這有兩種方法。 如果你使用NSArray很酷,我就是這個解決方案的粉絲。
let arr = [["EmpName" : "Alex", "Designation" : "Jr. Developer"],
["EmpName" : "Bob", "Designation" : "Sr. Developer"],
["EmpName" : "Claire", "Designation" : "Jr. Developer"],
["EmpName" : "David", "Designation" : "Project Manager"]]
let names = arr.map { (dictionary) -> String? in
return dictionary["EmpName"]
}
// names now contains array of names as String?
// If you want to use NSArray
let newArray = arr as NSArray
let newNames = newArray.valueForKeyPath("EmpName")
// newNames now contains array of names as String
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.