Swift 4 Upgrade Error: ‘init(colorLiteralRed:green:blue:alpha:)’ is unavailable

I upgraded a project to Swift 4 today and hit a compiler error:

‘init(colorLiteralRed:green:blue:alpha:)’ is unavailable: This initializer is only meant to be used by color literals.

The fix is pretty simple: Don’t use that initializer! (thank you, Captain Obvious!)

The correct initializer to use for specifying a red, green, blue, and alpha to get a UIColor instance in Swift 4 is:

UIColor(red:green:blue:alpha:)

So essentially, just replace colorLiteralRed:, and replace it with just red:, and the compiler error will go away. Here’s an example of how to call it:

let color = UIColor(red: 204/255, green: 204/255, blue: 204/255, alpha: 1.0)

comments powered by Disqus