jotape
jotape

Reputation: 319

Arrays as values in a Dictionary in Swift: Cannot append values

I want a function to append an object Something to an array of Somethings, as a value inside a Dictionary. If the key does not exist, I want to create it. If theDictionary[aCategory] is empty, It wont enter the if var statement (because is nil), so I really don't know how to solve it. I'm sure with force unwrapping I will solve it, but really want to use a more safe way, like optional biding.

private var theDictionary: [Category:[Something]] = [:]
public func add(aSomething: Something, aCategory: Category{
    if var arrayOfSomethings = theDictionary[aCategory]{
        arrayOfSomethings.append(aSomething)
        theDictionary[aCategory] = arrayOfSomethings
    }
}

Upvotes: 0

Views: 138

Answers (1)

Fahim
Fahim

Reputation: 3556

You just need to handle the else condition:

if var arrayOfSomethings = theDictionary[aCategory]{
    arrayOfSomethings.append(aSomething)
    theDictionary[aCategory] = arrayOfSomethings
} else {
    theDictionary[aCategory] = [aSomething]
}

Upvotes: 2

Related Questions