1

This is my custom data struct:

struct Absence {
    var type: String
    var date: TimeInterval
}

I have an array of this data struct like this:

var absences: [Absence]

I would like a function to return all the types of an absence. I have written this:

func types() -> [String] {
    var types = [String]()
    for absence in self.absences {
        if !types.contains(absence.type) {
            types.append(absence.type)
        }
    }
    return types
}

I was wondering if there was a better way of iterating through using either map, compactMap or flatMap. I am new to mapping arrays. Any help much appreciated.

1
  • 2
    Start with absences.map { $0.type }. Use a Set to get rid of duplicates. Commented Sep 4, 2020 at 19:36

1 Answer 1

1

You could just do the following:

var types = absences.map { $0.type }

If you would like to filter the types:

var types = absences.map { $0.type }.filter { $0.contains("-") }

Or if you simply want to remove all duplicates:

var types = Array(Set(absences.map { $0.type }))
Sign up to request clarification or add additional context in comments.

4 Comments

Swift 5.2 or later you can use KeyPath map(\.type)
@LeoDabus Was actually writing the same :)
Note that using a set like this you will discard the array original order. If you would like to preserve the original order of the elements check this post stackoverflow.com/a/34712330/2303865
Thank you everyone for your solutions - much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.