Acoop
Acoop

Reputation: 2666

Dictionary inside dictionary

I am trying to use a list that is a value for a dictionary key/pair set, and this dictionary is itself a value in a key/pair set in a dictionary. To explain, this is how I initialize it.

var dictOfEvents = [Int: [Int: [PFObject]]]()

I am trying to add events to the list, with the inner dictionary's key being the day of month and the outer one being the month. For example, an event on May 1 would be:

dictOfEvents[5:[1:[ListOfEvents]]

Where ListOfEvents is an array of PFObjects. Before I added the month functionality, and thus the outer dictionary, the way I added new events was: ` self.dictOfEvents[components.day] = [event] But now, when I try to extend this with:

self.dictOfEvents[components.month]?[components.day]! = [event]

It does not work. Any explanation on how to create new event lists and access this double layer dictionary would be greatly appreciated.

(Note: I don't know where to put the ! and the ? in the last piece of code so please excuse me if I made a mistake.)

Upvotes: 2

Views: 1633

Answers (2)

Zhengjie
Zhengjie

Reputation: 451

U can simple change:

self.dictOfEvents[components.month]?[components.day]! = [event]

to :

self.dictOfEvents[components.month]![components.day]! = [event]

Because Dictionary has subscript, Dictionary? doesn't have subscript.

if U try add Events to Dictionary. I suggest to use this:

var dictOfEvents = [Int: [Int: [PFObject]]]()

var dictOfDayEvents = [Int:[PFObject]]()

dictOfDayEvents.updateValue([PFObject()], forKey: 1)
dictOfEvents.updateValue(dictOfDayEvents, forKey: 5)

Upvotes: 1

Matteo Piombo
Matteo Piombo

Reputation: 6726

Here is what I think could be a good use of optionals in your case (and should respond to your question):

var dic: [Int: [Int: [String]]] = [:]
dic[5] = [1:["Hello", "World"]]

if let list = dic[5]?[1] {
    // your list exist and you can safely use it
    for item in list {
        println(item)
    }
}

I just used String instead of PFObject.

A different approach could be:

/*
Define a struct to encapsulate your Month and Day
Make it Hashable so that you can use it as Dictionary key
*/
public struct MonthDay: Hashable {
    let month: Int
    let day: Int
    public var hashValue: Int { return month * 100 + day }
}

public func ==(lhs: MonthDay, rhs: MonthDay) -> Bool {
    return lhs.month == rhs.month && lhs.day == rhs.day
}

var dictOfEvents = [MonthDay :[String]]()
let aMonthAndDay = MonthDay(month: 5, day: 1)

dictOfEvents[aMonthAndDay] = ["Hello", "World"]
if let list = dictOfEvents[aMonthAndDay] {
    // your list exist and you can safely use it
    for item in list {
        println(item)
    }
}

Upvotes: 1

Related Questions