简体   繁体   中英

using an array to subset an array in Swift4

This must be a really basic question. In languages like R you can take an array (swift syntax here)

let x = [1,2,3,4,5]

and extract multiple elements using an array of indices. That is I would like to be able to do something like say (now in a pseudo-Swift syntax because it does not parse)

x[[0,2,3]]

to get a return value of

[1,3,4]

but this does not work directly in Swift. Is there a standard way of doing this? I am currently using Swift4.

I'm not aware of anything built into the Swift Array class that does this.

One possible solution is to define an extension to Array that filters the array to only include the elements at the provided indices.

extension Array {
    func elements(at indices: [Int]) -> Array<Element> {
        return self.enumerated().filter { indices.contains($0.0) }.map { $0.1 }
    }
}

Example usage:

let x = [1,2,3,4,5]
let res = x.elements(at: [0,2,3])
print(res)

Output:

[1, 3, 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM