2

I'm trying to extend an array to return only objects at certain indexes. The map function seemed to be the best choice for me here.

extension Array {

    func objectsAtIndexes(indexes: [Int]) -> [Element?]? {
        let elements: [Element?] = indexes.map{ (idx) in
            if idx < self.count {
                return self[idx]
            }
            return nil
        }.filter { $0 != nil }
        return elements
    }
}

let arr = ["1", "2", "3", "4", "5"]
let idx = [1,3,5]

let x = arr.objectsAtIndexes(idx) //returns: [{Some "2"}, {Some "4"}]

I'm getting a EXC_BAD_INSTRUCTION error when I try to cast the result to a string array:

let x = arr.objectsAtIndexes(idx) as? [String]

enter image description here

Is there any way I can return an array of non-optionals? I've tried to return [Element]? from the extension function. This throws the same error.

Ron
  • 1,610
  • 15
  • 23

1 Answers1

2

The following code solves the problem for Swift2.1 using the flatmap function.

extension Array {

    func objectsAtIndexes(indexes: [Int]) -> [Element] {
        let elements: [Element] = indexes.map{ (idx) in
            if idx < self.count {
                return self[idx]
            }
            return nil
            }.flatMap{ $0 }
        return elements
    }
}
Ron
  • 1,610
  • 15
  • 23