【问题标题】:How to filter values in dictionary of type [Type: [Type]]()如何过滤类型为 [Type: [Type]]() 的字典中的值
【发布时间】:2019-06-26 19:29:57
【问题描述】:

我有一个包含多个值的字典,我想通过它过滤 nil 值。字典的类型是:

var dic = [Int: [String]]()

字典是:

var dic = [218: ["A", "B", "C",""],216: ["Q", "", "W",""]]

//remove the empty values
let filter = dic.filter({ !$0.value.isEmpty})
print(filter)

它返回与 nil 值相同的字典值,应该被删除。

【问题讨论】:

  • ["Q", "", "W",""] 的值不为空,严格来说,空字符串不是nil 的值
  • 我认为这是因为我在 let dic = ["a": "1", "b": "2", "c": "", "d ": "3"] let filter = dic.filter({ !$0.value.isEmpty}) print(filter) // 打印 ["a": "1", "b": "2", "d": "3"]

标签: swift dictionary swift4


【解决方案1】:

您似乎需要从"" 中过滤内部数组,这不是nil,而是代表您需要的空字符串

let filter = dic.mapValues { $0.filter { $0 != "" } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多