stevenpcurtis
stevenpcurtis

Reputation: 2001

Scope of if var closure on Swift

I'm implementing an adjacency list using Swift.

Now I want to addEdge, and if that value already exists in the dictionary I want to append a new edge.

However, the scope of if var seems to only be within the following closure, meaning

if var child = children[from] {
    // child exists
    child.append(to)
}

does not produce the intended result, but the following does

if var child = children[from] {
    children[from]!.append(to)
}

but this looks ugly and, frankly wrong.

What is the best way of appending to the dictionary in this case?

Upvotes: 1

Views: 108

Answers (1)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

Since your dictionary value is a value type [Int], a copy of the dictionary value is made and given to child. This means that any changes you make to child will not reflect in the dictionary. So, you need to replace the value with the one to which you have made the changes.

if var child = children[from] {
    child.append(to)
    children[from] = child
}

Or simply,

children[from]?.append(to)

Upvotes: 3

Related Questions