[Solved] Unable to convert this Swift 2 code to Swift 3


That line should have failed under any version of Swift for being so unwieldily.

First off, safely unwrap the optional. And only use one cast at the end.

func isLight() -> Bool {
    if let components = self.cgColor.components {
        let brightness = CGFloat((components[0] * 299 + components[1] * 587 + components[2] * 114) / 1000)

        return brightness > 0.5
    } else {
        return false
    }
}

This code assume the color is in the RGB colorspace. This code will fail otherwise (just like the original code would have failed).

Here’s a safer implementation that handles both RGB and grayscale colors:

func isLight() -> Bool {
    var brightness: CGFloat = 0
    var r: CGFloat = 0
    var g: CGFloat = 0
    var b: CGFloat = 0

    if self.getRed(&r, green: &g, blue: &b, alpha: nil) {
        brightness = (r * 299 + g * 587 + b * 114) / 1000
    } else {
        var w: CGFloat = 0
        if self.getWhite(&w, alpha: nil) {
            brightness = w
        }
    }

    return brightness > 0.5
}

3

solved Unable to convert this Swift 2 code to Swift 3