Swift Array instance method drop(at: Int)

2392 views arrays

Array in Swift has several instance methods for excluding elements, such as dropFirst(), dropLast(), drop(where:), etc. What about drop(at:)?

Note: I'd use remove(at:), but the array I'm working with is a constant.

answered question

1 Answer


How about using a Swift extension to add drop(at:) to the Array structure?

extension Array {
  func drop(at index: Int) -> ArraySlice<Element> {
    return self[0..<index] + self[index+1..<endIndex]

It returns a slice of the original array without the element at the specified index.

let numbers = [1, 2, 3, 4, 5]
print(numbers.drop(at: 2))
// Prints "[1, 2, 4, 5]"

posted this

Have an answer?


Please login first before posting an answer.