FlatMap Struct Multiple Properties

So I have a struct:

struct Category {
    let title: String
    let icons: [String]

And I want to extract all the strings out of it in order. For instance:

var categories = [Category]()
categories += [Category(title: "Title1", icons: ["icon1", "icon2"])]
categories += [Category(title: "Title2", icons: ["icon3", "icon4"])]

let strings = categories.flatMap({ [$0.title, $0.icons] })

What I want is:
["Title1", "icon1", "icon2", "Title2", "icon3", "icon4"]

But I keep getting:
["Title1", ["icon1", "icon2"], "Title2", ["icon3", "icon4"]]

Is this even possible? Thanks!

Hi @sprouse5,
if you write code, you can basically do whatever you want, so the short answer is yes, you can so that.

However it is a bit unusual to flatten all the elements.

update the code below into your code
let strings = categories.flatMap({ [$0.title, $0.icons.first!, $0.icons.last!] })
However this relies on the fact that you have exactly 2 elements in the icons array



Thanks for your reply! I’m flattening all the strings that I’m reading in from a plist file to get a single string array of categories for use in filtering later on in the app. My solution was to create a computed property like this:

struct Category {
    let title: String
    let icons: [String]

    var names: [String] {
        var strings = icons
        strings.insert(title, at: 0)
        return strings

I create a copy of the icons array, add the title to the beginning of it, and return it. That way I can flat map like so:

let data = categories.flatMap { $0.names }

If there’s a better/more efficient way to do this I’d like to know, as I’m trying to create this app using iOS best practices. Thanks for your time!

You can do it in one line with no extra property:

let data = categories.flatMap { [$0.title] + $0.icons }

The closure makes a one element array of title, then adds the icons array to that, much like your computed property.

1 Like

Thanks so much @sgerrard! This is exactly what I was after.

This topic was automatically closed after 166 days. New replies are no longer allowed.