Vivrd Prasanna
Vivrd Prasanna

Reputation: 103

How to make a dictionary with a 2D Array as Value?

I am trying to make a dictionary in Swift that looks like this:

["key1": [["val1", "val2", "val3"], ["vala", "valb", "valc"]], 
 "key2": [["test1", "test2", "test3"], ["testa", "testb", "testc"]]]

Right now, I have this code:

var lst1 = ["val1", "val2", "val3"]
var lst2 = ["vala", "valb", "valc"]
var lst3 = ["test1", "test2", "test3"]
var lst4 = ["testa", "testb", "testc"]

var str_to_array: [String: [String]] = [:]
str_to_array["key1"] = lst1

It gives me the output I am looking for when I print it, which is

["key1": ["val1", "val2", "val3"]]

However, when I try to push another list into the dictionary for the same key like this:

str_to_array.append(contentsOf: lst2)

I get this output:

["key1": ["val1", "val2", "val3", "vala", "valb", "valc"]

while I am looking for this:

["key1": [["val1", "val2", "val3"], ["vala", "valb", "valc"]]

var str_to_array: [String: Array] = [:] gives me an error, and placing double like this: var str_to_array [String: [[String]]] also gives me an error. What should I try now?

Upvotes: 0

Views: 718

Answers (1)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

Your dictionary should have an array of string arrays as value.

var lst1 = ["val1", "val2", "val3"]
var lst2 = ["vala", "valb", "valc"]
var lst3 = ["test1", "test2", "test3"]
var lst4 = ["testa", "testb", "testc"]

var dict: [String: [[String]]] = [:]

To store values, you should have a method which stores the list or appends the list with the existing list(s) if a value already exists.

func saveToDictionary(list: [String], withKey key: String) {
    dict[key, default: []].append(list)
}

saveToDictionary(list: lst1, withKey: "key1")
saveToDictionary(list: lst2, withKey: "key1")

print(dict)

Edit: Improved the answer after referring to this.

Upvotes: 1

Related Questions