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

Time:10-08

I have this model:

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

struct Field {
    var type: String
}

And this array:

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")]),
]

I would like to reduce all the types properties in a Set of Strings, I tried this:

let result = classes.map { $0.field.reduce([], { $0   $1.value.type }) }

But instead of getting a set of strings:

What I would like to get

"STRING", "NUMBER", "POINTER"

I get an array of characters:

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

What should I write instead? Thank you for your help

CodePudding user response:

You can use flatMap to flatten the arrays of values and then use Set to get rid of non-unique values:

let result = Set(classes.flatMap { $0.field.values }.map { $0.type })

If you need an Array instead of a Set, you can simply wrap the above in Array()

  • Related