0

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
    }
}

1 Answer 1

2

You just need to handle the else condition:

if var arrayOfSomethings = theDictionary[aCategory]{
    arrayOfSomethings.append(aSomething)
    theDictionary[aCategory] = arrayOfSomethings
} else {
    theDictionary[aCategory] = [aSomething]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Replace this entire block with theDictionary[aCategory, default: []].append(aSomething).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.