ImageStore error in Swift 3

In page 231, in the class ImageStore, you create the function:

func imageForKey(key: String) -> UIImage? {
    return cache.objectForKey(key) as? UIImage
}

In swift 3, Xcode suggests altering it to stop an error.

func imageForKey(key: String) -> UIImage {
    return (cache.object(forKey: key as NSObject) as? UIImage)!
}

Unfortunately, this fails to run on the simulator, immediately throwing up an error when I click on an item. On my device, it keeps trying to return but doesn’t do anything after.
It is clearly because it finds nil for the optional value in the simulator and force unwraps the optional. But I can’t find a way to get the function to work without throwing up an error and not force unwrapping.

Any help would be hugely appreciated!
Thank you!

Wow, I’m hella stupid. I forgot to put the optional symbol in the returned UIImage. /thread :slight_smile:

why you changed return value from “UIImage?” to “UIIMage” ?

It’s something also suggested by the compiler or just a typo?

Because return value has to stay as it was (Optional) in order to function without crash.

Of course removing “?” compiler start complaint about missing exclamation mark because

cache.object(forKey: key as NSObject)

is of Optional<UIImage> type