Reputation: 438
I attempted the syntax in the following way:
var Days: [String: (Dictonary [Int: Int])] = ["ADay: : [:], "BDay" : [:], "CDay" : [:], "DDay:" : [:]]
I wish to then set them later like so:
Days.ADay = [1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7]
Days.BDay: [Int: Int] = [1:8, 2:1, 3:2, 4:3, 5:4, 6:5, 7:13]
etc.
Thanks.
Upvotes: 2
Views: 15223
Reputation: 72855
Creating a nested dictionary in Swift is easy. In its simplest form, the most intuitive way is:
let dict = ["key": ["nestedKey": ":)"]]
In your case, for starters, your quotations are mismatched.
Next, you're overthinking what a dictionary is and how you instantiate it. You're trying to build a predefined dictionary with nested keys (which are actually immutable). If you want to do it your way, don't worry about pre-defining keys. When you're ready to assign, do:
var days: [String: Dictionary] = []
days["ADay"] = [1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7]
If you need something more complex, or something more structured than that, try using a Struct instead. This is the "Swift" way of doing things, allowing you to structure a complex set of conforming (statically typed!) data. Example:
struct Days {
var ADay = [Int: Int]()
var BDay = [Int: Int]()
var CDay = [Int: Int]()
var DDay = [Int: Int]()
}
var days = Days()
days.ADay = [1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7]
Upvotes: 9
Reputation: 855
If you're looking for a shorthand type declaration it would look like this.
var twodDict: [String : [String : Int]]
In other words:
var twodDict: [OuterKey : [InnerKey : StoredObjectorValue]]
Upvotes: 1
Reputation: 82535
Here are your examples with legal syntax:
var Days: [String: [Int: Int]] = ["ADay": [:], "BDay" : [:], "CDay" : [:], "DDay:" : [:]]
Days["ADay"] = [1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7]
Days["BDay"] = [1:8, 2:1, 3:2, 4:3, 5:4, 6:5, 7:13]
Another way to declare your type is var Days: Dictionary<String, Dictionary<Int, Int>>
.
Upvotes: 1