ios - Dictionary inside dictionary -
i trying use list value dictionary key/pair set, , dictionary value in key/pair set in dictionary. explain, how initialize it.
var dictofevents = [int: [int: [pfobject]]]()
i trying add events list, inner dictionary's key being day of month , outer 1 being month. example, event on may 1 be:
dictofevents[5:[1:[listofevents]]
where listofevents
array of pfobjects
. before added month functionality, , outer dictionary, way added new events was: ` self.dictofevents[components.day] = [event] now, when try extend with:
self.dictofevents[components.month]?[components.day]! = [event]
it not work. explanation on how create new event lists , access double layer dictionary appreciated.
(note: don't know put ! , ? in last piece of code please excuse me if made mistake.)
here think use of optionals in case (and should respond question):
var dic: [int: [int: [string]]] = [:] dic[5] = [1:["hello", "world"]] if let list = dic[5]?[1] { // list exist , can safely use item in list { println(item) } }
i used string
instead of pfobject
.
a different approach be:
/* define struct encapsulate month , day make hashable can use 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] { // list exist , can safely use item in list { println(item) } }
Comments
Post a Comment