Search code examples
arraysswift

New Array from Index Range Swift


How can I do something like this? Take the first n elements from an array:

newNumbers = numbers[0..n]

Currently getting the following error:

error: could not find an overload for 'subscript' that accepts the supplied arguments

EDIT:

Here is the function that I'm working in.

func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
    var newNumbers = numbers[0...position]
    return newNumbers
}

Solution

  • This works for me:

    var test = [1, 2, 3]
    var n = 2
    var test2 = test[0..<n]
    

    Your issue could be with how you're declaring your array to begin with.

    EDIT:

    To fix your function, you have to cast your Slice to an array:

    func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
        var newNumbers = Array(numbers[0..<position])
        return newNumbers
    }
    
    // test
    aFunction([1, 2, 3], 2) // returns [1, 2]