-1

Say i have an array for objects

let persons = [Person]

struct Person { 
    let name: String
    let position: Int
}

And i wanna return array of strings [String] containing persons' names whose position is equal to 1. If there any way to do this using map/flatmap/reduce functions?

eugene_prg
  • 948
  • 2
  • 12
  • 25
  • 3
    When posting a question like this you should include your own attempt at solving the issue instead of treating stackoverlow like a free code writing service. – Joakim Danielson Jun 04 '20 at 10:49

2 Answers2

1

Here's how:

let names = persons
    .filter { $0.position == 1 }
    .map { $0.name }
Frankenstein
  • 15,732
  • 4
  • 22
  • 47
1

To avoid two steps use compactMap

let positionOneNames = persons.compactMap{$0.position == 1 ? $0.name : nil }
vadian
  • 274,689
  • 30
  • 353
  • 361