Dictionary of Dictionaries

Hello,

I have a question regarding a Dictionary of Dictionaries. Is there a shorter way to put single elements in the Dict than I did?

var cellHeight = [ Int : [ Int : CGFloat ] ]()

// ...

if let _ = cellHeight[0] {
    cellHeight[0]![2] = 0.0
} else {
    cellHeight[0] = [ 2 : 0.0 ]
}

In all the tutorials I checked it’s only explained how to fill/initialize the full dict-of-dict and than read from it, but not how to fill it part by part.

Thanx

alex

Do you wish to fill a dictionary of dictionaries with automatically in the sense that you want to one-time-migrate data to the structure?

Or do you wish to capture user data in some way and put it into a dictionary-of-dictionaries?

I don’t think there’s a built-in way to do what you did, better than you did. How about this?

public extension Dictionary {
	subscript(
		key: Key,
		@autoclosure valueAddedIfNil Value: () -> Dictionary.Value
	) -> Dictionary.Value {
		mutating get {
			return self[key] ?? {
				self[key] = Value()
				return self[key]!
			}()
		}
		set {self[key] = newValue}
	}
}
cellHeight[0, valueAddedIfNil: [:]][2] = 0