user2924482 user2924482 - 26 days ago 10
iOS Question

Swift: Initialize 2D array (error: contextual type 'Int' cannot be used with array literal)

I'm trying to create 2D array of Integers:

var arr: [[Int]] = []
arr[0][0] = [123, 456, 789]


But I'm getting the following error in the second line:

error: contextual type 'Int' cannot be used with array literal
arr[0][0] = [123, 456, 789]


Any of you knows how can I add the int values to the 2D array with no errors?

I want to add the following values in the 2D array:

[123, 456, 789]
[2, 3, 5]
[100, 300, 400]


I'll really appreciate your help.

Answer

arr[0][0] is a single Int, but you're trying to assign [123, 456, 789] to it, which is an [Int] (a.k.a. Array<Int>).

You can nest Array literals to achieve what you want:

let array = [ //inferred type: [[Int]]
    [123, 456, 789],
    [  2,   3,   5],
    [100, 300, 400],
]