Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster way to get multiple elements from an array in Swift?

Is there a faster/more concise way to get multiple indexes from an array besides looping, and appending? Maybe a one-liner functional variant of the following?

let names: [String] = ["John", "Mary", "Hugo", "Bill", "Andrea"]
let indexesToGet = [0, 1, 3]
var result: [String] = []
for i in 0..<indexesToGet.count {
    result.append(names[indexesToGet[i]])
}
return result
//returns ["John", "Mary", "Bill"]
like image 290
MH175 Avatar asked Jan 09 '17 05:01

MH175


People also ask

How do you find multiple elements in an array?

To check if multiple values exist in an array:Use the every() method to iterate over the array of values. On each iteration, use the indexOf method to check if the value is contained in the other array. If all values exist in the array, the every method will return true .

Which is faster set or array Swift?

Difference between an Array and Set in SwiftArray is faster than set in terms of initialization. Set is slower than an array in terms of initialization because it uses a hash process.

What is .first in Swift?

first(where:) Returns the first element of the sequence that satisfies the given predicate.

What is array capacity in Swift?

The total number of elements that the array can contain without allocating new storage.


1 Answers

You can try like this.

let result = indexesToGet.map { names[$0] }

To prevents from indexOutOfBounds crash you can use flatMap.

let result = indexesToGet.flatMap { (names.count > $0) ? names[$0] : nil}

From Swift 4.1 use compactMap instead of flatMap.

let result = indexesToGet.compactMap { (names.count > $0) ? names[$0] : nil}
like image 80
Nirav D Avatar answered Oct 03 '22 23:10

Nirav D