'Cannot assign value of type 'UIImage??' to type 'UIImage?' Swift 5

Why does swift(Xcode) requires a "!!" double exclamation mark after using randomElement() to an UIImage array, it by itself gives me an error.

Example:

someView1.image = viewArray.randomElement()   // right here it tells me to put !!

after putting the "!!" at the end everything works fine. Why?



Solution 1:[1]

The problem is that viewArray is not an array of UIImage. It is an array of Optional UIImage. Well, calling randomElement() itself adds a level of Optionality, because the array itself might be empty. Thus you get an Optional wrapping an Optional wrapping a UIImage.

Simple solution: say

viewArray.compactMap {$0}.randomElement()

That unwraps the Optionals in the array. Now randomElement yields an Optional. You will still need to unwrap it if you want a UIImage, but at least there will be only one level to unwrap.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 matt