Value of optional type 'UIColor?' must be unwrapped to a value of type 'UIColor'

Viewed 1321

Using

self.backgroundColor = .init(named: "my-color")

where self is an UIView, triggers this error:

Value of optional type 'UIColor?' must be unwrapped to a value of type 'UIColor'
Coalesce using '??' to provide a default when the optional value contains 'nil' [Fix]
Force-unwrap using '!' to abort execution if the optional value contains 'nil' [Fix]

The compiler knows that the backgroundColor property is of type UIColor?, so it should infer it for the initializer, right?

Moreover, knowing that the property is optional, the error message doesn't make too much sense for me.

Also, both auto fixes are "recursive", meaning that they don't fix the error, and I can apply them over and over again.

Note: I know that I can use UIColor.init or simply UIColor. This is just a simplified example.

2 Answers

I think this error doesn't make sense and, after some research, I found it's actually a known bug in Swift. The reference is here.
Basically, it seems the compiler tries to look through the optional to find your initializer.
It seems the fix will be shipped with the next release.

backgroundColor is declared as optional. The compiler infers UIColor? and tries to create

self.backgroundColor = UIColor?.init(named: "my-color")

which is not supported – and which is not related to the optional init method.


You must use the non-optional type

self.backgroundColor = UIColor(named: "my-color")
Related