RXP
RXP

Reputation: 677

How to collect all elements to an array from a custom Object in swift 5

I just started learning Swift and I come from a Java background. I am looking to figure out how to collect elements of an array of objects to an array. see example below:

struct Employee {
    var name: String
    var age: Double
    var height: Double
    var weight: Double
}

let employees = [Employee]()

with the above Employee object, I have a list of employees in an array. I would like to collect all the ages into an array similar to a lambda expression in Java.

In Java 8 you could do:

double[] ages = employees.stream().mapToDouble(x -> x.age).toArray()

thanks in advance

Upvotes: 1

Views: 1335

Answers (1)

gcharita
gcharita

Reputation: 8327

You can just use map(_:) function like that:

let ages = employees.map { $0.age }

Update: As @LeoDabus said in the comments, since Swift 5.2, map(_:) function can be used with KeyPath for an even more elegant approach:

let ages = employees.map(\.age)

Upvotes: 3

Related Questions