Swift:根据键将字典数组转换为字符串数组

Swift: Convert Array of Dictionaries to Array of String based on a key

以下是我的字典数组,我想获得一个仅包含基于特定键(在我的例子中是 contentURL 键)的字符串的数组。

如何实现?我遇到过 Reduce & Filter 但没有一个符合我的要求。

(
  {
    contentURL = "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4";
  },
  {
    contentURL = "https://d1shcqlf263trc.cloudfront.net/151021804847312.mp4";
  },
  {
    contentURL = "https://d1shcqlf263trc.cloudfront.net/151021536556612.mp4";
  },
  {
    contentURL = "https://d1shcqlf263trc.cloudfront.net/151021528690312.mp4";
  }
)

Expected Output

[
  "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4", 
  "https://d1shcqlf263trc.cloudfront.net/151021804847312.mp4",
  "https://d1shcqlf263trc.cloudfront.net/151021536556612.mp4", 
  "https://d1shcqlf263trc.cloudfront.net/151021528690312.mp4"
]
var stringArray:[String] = []
for (key, value) in yourArrayOfDictionary {
    stringArray.append(value)
} 
var myDict: [[String : String]] = [["contentURL" : "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4"],["contentURL" : "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4"],["contentURL" : "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4"]]
let arr = myDict.map { [=10=]["contentURL"] }

只需使用compactMap

 let array = arrayOfDicts.compactMap {[=10=]["contentURL"] }
var arrayDict = [["contentURL":"fd"],["contentURL":"fda"],["contentURL":"fdb"],["contentURL":"fdc"]]

let arraywithOptionstring = arrayDict.map{[=10=]["contentURL"]}
        if let arr = arraywithOptionstring as? [String]{
             print(arr)
        }

预期输出:["fd"、"fda"、"fdb"、"fdc"]

如果你想使用 reduce:

let arr = [
    ["contentURL" : "https://d1shcqlf263trc.cloudfront.net/"],
    ["contentURL" : "https://d1shcqlf263trc.cloudfront.net/.mp4"],
    ["contentURL" : "https://d1shcqlf263trc.cloudfront.net/1510232473240ab.mp4"]
]


let only = arr.reduce([String]()) { (partialRes, dictionary) -> [String] in
    return partialRes + [dictionary["contentURL"]!]
}

更紧凑的版本:

let compact = arr.reduce([String]()) { [=11=] + [["contentURL"]!] }

可能您无法使用 reduce,因为您需要记住下标字典 returns 一个与 String

不同类型的 Optional

在这种情况下,您也可以只使用 .map

let array = arrayOfDicts.map {[=10=]["contentURL"]! }