Simon R
Simon R

Reputation: 3772

Issue with Swift: value of optional type '[Int : Int]?' not unwrapped; did you mean to use '!' or '?'?

I'm currently learning swift and I'm trying to create a function which will update a story based on which button is pressed. I already have the button press bit set up but then I pass the tag of the button pressed to the updateStory function.

func updateStory(myTag: Int) {

    let next = [
        1 : [
            1 : 3,
            2 : 2,
        ],
        2 : [
            1 : 3,
            2 : 4,
        ],
        3 : [
            1 : 6,
            2 : 5,
        ]
    ]

    // Error:(86, 17) value of optional type '[Int : Int]?' not unwrapped; did you mean to use '!' or '?'?
    if (next[storyIndex][myTag] != nil) {
        let nextStory = next[storyIndex][myTag]
        storyIndex = nextStory
    }

}

StoryIndex is defined as a global variable within the class.

Any pointers would be much appreciated.

Upvotes: 0

Views: 1096

Answers (1)

vacawama
vacawama

Reputation: 154613

Because dictionary look ups return an optional (the key might be missing), you need to unwrap the result of next[storyIndex] before you can index it. Use ? (optional chaining) here to safely unwrap the value. Since you need the result, instead of comparing to nil, use if let (optional binding):

if let nextStory = next[storyIndex]?[myTag] {
    storyIndex = nextStory
}

If storyIndex is not a valid key, then next[storyIndex] will be nil, and the result of the optional chain will be nil. If myTag is not a valid key, the result will also be nil. In the case that both keys are valid, the result of the optional chain will be Int? and nextStory will be bound to the unwrapped value.


If you have a default value to use for storyIndex (such as 1) if the look ups fail, you can use the nil coalescing operator ?? also with the optional chain to do this in one line:

storyIndex = next[storyIndex]?[myTag] ?? 1

or (to leave storyIndex unchanged for lookup failure):

storyIndex = next[storyIndex]?[myTag] ?? storyIndex

Upvotes: 6

Related Questions