Search code examples
iosarraysswiftmultidimensional-arrayswift-playground

Swift Issue - Dictionary with Two-dimensional Array in Array list


I am trying to figure it out what is wrong with my code because XCode doesn't accept to run this code. Any idea what is wrong with it?

var dictionary = [String: [[String]]]()
var array = [[AnyObject]]()

dictionary["1"] = [["A", "A"], ["A1", "A2"]]
dictionary["2"] = [["B", "B"], ["B1", "B2"]]
dictionary["3"] = [["C", "C"], ["C1", "C2"]]

for i in 1...3 {
    array.appendContentsOf([dictionary["\(i)"]!])
}

print(array)

This is what I am planning to have like this output:

[[["A", "A"], ["A1", "A2"]], [["B", "B"], ["B1", "B2"]], [["C", "C"], ["C1", "C2"]]]

This what I got an error from Xcode:

An internal error occurred. Source editor functionality is limited.

Note: The most bizarre part about this if I removed this line: array.appendContentsOf([dictionary["(i)"]!]) and it doesn't have an error but if I added this line then I got an error from Xcode


Solution

  • You were very close! A couple changes:

    1. array needed to be defined as [[[String]]]() instead of [[AnyObject]](). AnyObject and String are not compatible for appending. Also, another layer of [] was added as your goal was an array 3 deep, not 2.
    2. Changed array.appendContentsOf([dictionary["\(i)"]!]) to array += [dictionary["\(i)"]!] as this is compatible across all versions of Swift and keeps the appended argument from being unwrapped.

    This provides the correct answer (tested in Swift Playground):

    var dictionary = [String: [[String]]]()
    var array = [[[String]]]()
    
    dictionary["1"] = [["A", "A"], ["A1", "A2"]]
    dictionary["2"] = [["B", "B"], ["B1", "B2"]]
    dictionary["3"] = [["C", "C"], ["C1", "C2"]]
    
    for i in 1...3 {
        array += [dictionary["\(i)"]!]
    }
    
    // console: 
    // [[["A", "A"], ["A1", "A2"]], [["B", "B"], ["B1", "B2"]], [["C", "C"], ["C1", "C2"]]]
    print(array)