user2924482
user2924482

Reputation: 9120

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.

Upvotes: 1

Views: 363

Answers (2)

dfrib
dfrib

Reputation: 73176

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

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

You could achieve this in a few different manners.

Simply include the sub-arrays at array initialization

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

This allows you to let arr be an immutable (let arr = ...), in case all the sub-arrays are known at compile time, and you know you wont need to mutate arr at a later time.

In case the content of your array is not fully known at compile time: you could use append(...) to add sub-arrays one by one when available

In case the sub-arrays are not available at the time of arr instantiation, you could use the += operator for arrays, or the append(_:) method, to dynamically add sub-arrays to array when they are provided

var arr = [[Int]]()

// ... at some later (run-)time point    
let somSubArrProvidedAtRuntime = [100, 300, 400]
arr.append(somSubArrProvidedAtRuntime)
// ....

As an alternative to append(_:), add a number of sub-arrays at once using append(contentsOf:)

Given the same case above, but where a number of sub-arrays are provided at once, you could use the append(contentsOf:) method to append several sub-arrays to the array at once

// some (one) sub-arr known at initialization
var arr = [[123, 456, 789]]

// some sub-arrays provided at runtime, a time later 
// than initialization
let subArrB = [2, 3, 5]
let subArrC = [100, 300, 400]

// ... using the `+=` operator for arrays
arr += [subArrB, subArrC]

// ... alternatively, using append(contentsOf:)
arr.append(contentsOf: [subArrB, subArrC])

Upvotes: 2

Alexander
Alexander

Reputation: 63167

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],
]

Upvotes: 2

Related Questions