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"]
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 .
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.
first(where:) Returns the first element of the sequence that satisfies the given predicate.
The total number of elements that the array can contain without allocating new storage.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With