Skip to content

Instantly share code, notes, and snippets.

@aaronlab
Created November 4, 2021 05:50
Show Gist options
  • Save aaronlab/42287bb219ea0bb582d78cf657ec18ec to your computer and use it in GitHub Desktop.
Save aaronlab/42287bb219ea0bb582d78cf657ec18ec to your computer and use it in GitHub Desktop.
Selected Elements by Selected Indexes
import Foundation
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8]
let selectedIndexes = [0, 1, 3, 5, 7]
extension Array {
subscript (safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
let selectedElements = selectedIndexes
.compactMap { array[safe: $0] }
print(selectedElements)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment