Anton Anton - 5 months ago 15
Swift Question

array elements as argument in functions

New to swift. We have

var b : [Double] = [0,1,2,3,4,5,6,7,8,9]
var c = 5


I want to call func xyz with first c elements of b.

var a = xyz(b[0...c])
- doesnt work

Answer

Using a Range to pick in an array generates an ArraySlice, not an Array.

So if you wish to pass this "slice" to a function:

var b : [Double] = [0,1,2,3,4,5,6,7,8,9]
var c = 5

let slice = b[0...c]

you have to make your function accept an ArraySlice with the right type:

func xyz(chunk: ArraySlice<Double>) {
    print(chunk)
}

xyz(slice)

But if you want to just use normal arrays, make your function accept an array, and transform the slice into an array when calling the function:

func xyz(chunk: [Double]) {
    print(chunk)
}

xyz(Array(slice))