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.

Tahmid Azam
  • 566
  • 4
  • 16

1 Answers1

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 }))
finebel
  • 2,227
  • 1
  • 9
  • 20