Swift: 如何用一行代码减少Set中的一些子元素?

Swift: how to reduce some sub-elements in a Set with a one-liner?

我有这个型号:

struct Class {
    var field: [String: Field]
}

struct Field {
    var type: String
}

这个数组:

let classes: [Class] = [
    Class(field: ["test": Field(type: "STRING"),
                  "test2": Field(type: "STRING"), 
                  "test3": Field(type: "NUMBER")]),
    Class(field: ["test": Field(type: "POINTER"),
                  "test2": Field(type: "STRING"), 
                  "test3": Field(type: "STRING")]),
]

我想减少一组字符串中的所有 types 属性,我试过这个:

let result = classes.map { [=13=].field.reduce([], { [=13=] + .value.type }) }

但不是获取一组字符串:

我想得到什么

"STRING", "NUMBER", "POINTER"

我得到一个字符数组:

[["S", "T", "R", "I", "N", "G", "N", "U", "M", "B"....]]

我应该写什么?感谢您的帮助

您可以使用 flatMap 展平值数组,然后使用 Set 去除非唯一值:

let result = Set(classes.flatMap { [=10=].field.values }.map { [=10=].type })

如果您需要 Array 而不是 Set,您可以简单地将上面的内容包装在 Array()