Joe Huang
Joe Huang

Reputation: 6570

How to initialize an array inside a dictionary?

I have a dictionary declared like this:

var myDict = [Int : [Int]]()

The array in it is not initialized, so every time I have to check it first:

if (myDict[idx] == nil) {
    myDict[idx] = []
}

How to initialize it as an empty array in MyDict declaration?

Upvotes: 0

Views: 497

Answers (3)

Pradeep K
Pradeep K

Reputation: 3661

You can initialize it this way

myDict.forEach {
    (var dictElement) -> () in
    dictElement.1 = [Int]()
}

Upvotes: 0

Jordan Smith
Jordan Smith

Reputation: 10378

I think you could be misunderstanding something pretty key - let's make sure:

The way the dictionary works, is not to have one array, but an array for each key.

Each value of 'idx' you request the array for returns a different array.

You can't expect it to return an empty array - a dictionary is meant to return a nil value for a key that hasn't been set. To do what you're trying, the following would probably do the trick:

myDict[idx] = myDict[idx] ?? []

Upvotes: 1

Nick Allen
Nick Allen

Reputation: 1873

That's what dictionary do if you try to retrieve a key for which no value exists. You can subclass Dictionary and override the subscript func to get what you want like this. Or simply write an extension, or write a operator defination to use a different symbol.

“You can also use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. ”

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2.1).” iBooks. https://itunes.apple.com/cn/book/swift-programming-language/id881256329?l=en&mt=11

Upvotes: 0

Related Questions