dmscs
dmscs

Reputation: 285

Is there a faster/better way to do this simple iteration in Swift?

for node in nodes{
    names.append(node.name)
}

I just wrote this code and it felt like I was doing it the slow/noob way, thinking about my experiences with Python and Swift so far, and just thought I should ask.

Upvotes: 2

Views: 224

Answers (2)

rob mayoff
rob mayoff

Reputation: 385660

You didn't show the declaration of names. I'll assume your code looks like this:

var names: [String] = []
for node in nodes {
    names.append(node.name)
}

If so, you could write it like this:

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

or like this:

let names = nodes.map(\.name)

On the other hand, if names might already contain some values you want to preserve, you could do this:

names.append(contentsOf: nodes.lazy.map(\.name)

The use of .lazy here prevents Swift from creating a temporary array just to hold the new names.

Upvotes: 6

matt
matt

Reputation: 535231

You are looking for map. Assuming that names doesn't exist when we start, you could just say

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

Upvotes: 3

Related Questions