【问题标题】:Iterate through the array of Dictionary and separate the name for status true遍历 Dictionary 的数组,并将 status 的名称分开为 true
【发布时间】:2018-10-02 16:03:50
【问题描述】:

我想遍历这个数组并分离出状态为 true 的名称。

var array = [["name":"joe", "status":false ],["name":"will", "status":false],["name":"smith" , "status":false]]

【问题讨论】:

  • 你的输出应该是什么样的?一个名为“joe”的数组?或数组与["name":"joe", "status":false ]?
  • 在这里提问之前你有没有尝试过?
  • 仅名称数组@Allen R

标签: swift swift3


【解决方案1】:

这应该可以解决问题。

var array = [["name":"joe", "status":true ],["name":"will", "status":true],["name":"smith" , "status":false]]

let filteredDictionary = array.filter( { $0["status"] as? Bool ?? false } )

var names = [String]()

for dictionary in filteredDictionary {
    if let nameFound = dictionary["name"] as? String {
        names.append(nameFound)
    }
}

我建议您使用struct 来存储值而不是字典。像这样。

struct Person {
    var name: String
    var status: Bool
}

如果你在 Person 数组中这样设置,它会变得不那么复杂,因为可以避免字典值可选处理。

var personArray = [Person(name: "joe", status: true), Person(name: "will", status: false)
let names = personArray.filter( {$0.status} ).map( {$0.name} )

【讨论】:

    【解决方案2】:

    您可以使用简单的filter 来保留状态和名称,否则使用compactMap 是您只想保留名称。

    let statuses = [["name":"joe", "status":true ],["name":"will", "status":false],["name":"smith" , "status":false]]
    let trueStatuses = statuses.filter({$0["status"] as? Bool == true}) // [["name": "joe", "status": true]]
    let namesWithTrueStatus = statuses.compactMap{$0["status"] as? Bool == true ? $0["name"] as? String : nil} //["joe"]
    

    【讨论】:

    • 为什么不简单地let namesWithTrueStatus = trueStatuses.compactMap{ $0["name"] as? String }
    • 我可以使用任何替代方法使用这样的 for 循环 for i in array { for (name,status) in i { } }
    • @LeoDabus 需要连续的 filtercompactMap 操作,所以即使代码看起来有点简单,但与单个 compactMap 相比,它的性能较差
    • @frieas 是的,你可以,但你为什么要这样做? compactMap 更加简洁干净
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 2017-10-28
    • 2022-07-16
    • 1970-01-01
    相关资源
    最近更新 更多