0

I have my object:

struct Person {
    var name = ""
    var age = 0
}

I have added some persons to an array:

let p1 = Person(name: "Tony", age: 10)
let p2 = Person(name: "Lisa", age: 20)
let p3 = Person(name: "Anna", age: 30)
let p4 = Person(name: "Morgan", age: 40)
let p5 = Person(name: "Jane", age: 50)

let persons = [p1, p2, p3, p4, p5]

I want all the names in a separate array but I don´t want to do like nameArray.append(p1.name)... Is it any other way to do this?

0

2 Answers 2

1

You could simply map the name:

let names = persons.map({ $0.name }) // ["Tony", "Lisa", "Anna", "Morgan", "Jane"] 
Sign up to request clarification or add additional context in comments.

3 Comments

Worked fine thanks!
@JaneDoe If you think an answer helped you, you can accept it by clicking on that checkmark!
Just to add to this, the map method is basically a shortcut to looping through the collection, performing actions on each element, and then appending a result to a new Array. Here’s a good guide on it and also filter and reduce.
0

Use the map function:

let names = persons.map { $0.name }

This may look like magic, so let's expand this to see what exactly is going on:

let names = persons.map ({
    person in
    return person.name
})

What happens here is that map applies a "transformation" to each Person in the array. And you specify what transformation to do by passing a closure to the map function. Here you say that "when you give me a person, I give you back the name of the person". See the transformation here? We transformed a person to just a name! map automatically applies this to every item in the array and appends all the results of the transformations to a new array.

Comments