Shadros
Shadros

Reputation: 798

Swift dictionary, a key with multiple values

I would like to know how I can make a key of a dictionary have multiple values according to the data that comes to it.

Attached basic example:

var temp = [String: String] ()

temp ["dinningRoom"] = "Table"
temp ["dinningRoom"] = "Chair"

In this case, I always return "Chair", the last one I add, and I need to return all the items that I am adding on the same key.

In this case, the "dinningRoom" key should have two items that are "Table" and "Chair".

Upvotes: 1

Views: 14488

Answers (3)

Syed Qamar Abbas
Syed Qamar Abbas

Reputation: 3677

You can use Swift Tuples for such scenarios.

//Define you tuple with some name and attribute type
typealias MutipleValue = (firstObject: String, secondObject: String)

var dictionary = [String: MutipleValue]()
dictionary["diningRoom"] = MutipleValue(firstObject: "Chair", secondObject: "Table")

var value = dictionary["diningRoom"]
value?.firstObject

Upvotes: 4

Use Dictionary like this:

var temp = [String: Any]()

temp["dinningRoom"] = ["Table", "Chair"]

If you want to fetch all the elements from dinningRoom. You can use this:

let dinningRoomArray = temp["dinningRoom"] as? [String]

for room in dinningRoomArray{
    print(room)
}

It is not compiled code but I mean to say that we can use Any as value instead of String or array of String. When you cast it from Any to [String] using as? the app can handle the nil value.

Upvotes: 2

Shadros
Shadros

Reputation: 798

You can declare a dictionary whose value is an array and this can contain the data you want, for example:

var temp = [String: [String]]()

temp["dinningRoom"] = ["Table", "Chair", "Bottle"]

If you want to add a new element you can do it this way:

if temp["dinningRoom"] != nil {
    temp["dinningRoom"]!.append("Flower")
} else {
    temp["dinningRoom"] = ["Flower"]
}

Now temp["dinningRoom"] contains ["Table", "Chair", "Bottle", "Flower"]

Upvotes: 5

Related Questions