New Array from Index Range Swift

前端 未结 5 1651
傲寒
傲寒 2020-12-02 07:41

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

newNumbers = numbers[0..n]

Currently getting the following error

5条回答
  •  无人及你
    2020-12-02 08:23

    This works for me:

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

    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, position: Int) -> Array {
        var newNumbers = Array(numbers[0..

提交回复
热议问题