Swift:从数组中的结构体中过滤一个字典键,可选

Swift: Filter a dictionary key from a struct from an array, which is optional

struct Test {
    var title: String
    var message: [String?: String?]

    init(title: String, message: [String?:String?]) {
        self.title = title
        self.message = message
    }
}

var cases = [
     Test(title: "1", message: ["tag1": nil]),
     Test(title: "2", message: ["tag2": "preview2"]),
     Test(title: "3", message: [nil:nil]),
     Test(title: "4", message: ["tag1":"preview4"])
]

现在,我想要:

  1. 一个数组,其中包含案例中消息 属性 中的所有键 - tag1 和 tag2(其中没有 nils)。我只是尝试了我所知道的一切,我做不到。尝试过滤案例,得到了选项。

  2. 没有标签就没有预览,所以不需要数组。我只需要一个带有标签的列表,以便对其进行排序并显示案例中的相关预览。这就是为什么我需要知道如何从案例中访问这些预览的原因。让我们在 UITableView 中说:

    cell.previewLabel?.text = cases[indexPath.row].preview[//No idea what here]
    

当然,有[tags: previews]的字典就完美了!

提前致谢!我希望我想要的是可能的。

这是一个仅包含来自 cases 的元素的数组,这些元素的所有键和值都不是 nil :

let filtered = cases.filter { test in
    return test.message.allSatisfy({ entry in
        return entry.key != nil && entry.value != nil
    })
}

或使用 shorthand 表示法:

let filtered = cases.filter {
    [=11=].message.allSatisfy({
        [=11=].key != nil && [=11=].value != nil
    })
}

对于结构,有一个默认的初始值设定项,因此您可以这样编写 Test 结构:

struct Test {
    var title: String
    var message: [String?: String?]
}

我不完全清楚您要做什么,但是,这会将您的 cases 数组过滤为仅包含 non-nil 的 Test objects values 在消息字典中:

let nonNil = cases.filter { (test) -> Bool in
    return Array(test.message.values).filter({ (value) -> Bool in
        return value == nil
    }).count <= 0
}

变量 nonNil 现在包含 Test objects,其中标题为“2”,标题为“4”。

如果您想要 [tags:preview] 字典,您可以进一步过滤。像这样的东西可以做到这一点:

let tags = nonNil.map( { [=11=].message} ).flatMap { [=11=] }.reduce([String:String]()) { (accumulator, current) -> [String:String] in
    guard let key = current.key, let value = current.value else { return accumulator }
    var accum = accumulator
    accum.updateValue(value, forKey: key)
    return accum
}

tags 词典现在包含:["tag1": "preview4", "tag2": "preview2"]