How to get a subArray from Swift 2.0

Skyler Lauren picture Skyler Lauren · Oct 11, 2015 · Viewed 19.5k times · Source

I keep trying to search for the proper way to get a sub array in Swift but I am missing something here. This code doesn't work because rowArray.append(row) throws an error that states.

Cannot convert value of type 'ArraySlice<Int>' to specified type '[Int]'

I can't figure out how to get an [Int] out of the main array or to convert ArraySlice<Int> to [Int]. I am guessing I am missing something simple but can't seem to find the answer from the docs.

var rowArray = [[Int]]()

var rangeStart = 0
let rangeLength = mapWidth

for var index = 0; index < mapHeight; ++index{
    rangeStart = tileIDs.count - ((index + 1) * mapWidth )

    let row : [Int] = tileIDs[rangeStart...rangeStart+rangeLength]
    rowArray.append(row)
}
rowArray.append(row)

Answer

Eric Aya picture Eric Aya · Oct 11, 2015

Convert ArraySlice<Int> to [Int] with Array():

let row : [Int] = Array(tileIDs[rangeStart...rangeStart+rangeLength])