snapchatdotcom snapchatdotcom - 4 months ago 33
Objective-C Question

Ambiguous use of operator "+=" for converting color?

I'm trying to convert this objective-code to swift:


Objective-C Version


+ (NSNumber *)serializeColor:(UIColor *)color
{

uint32_t integer = 0;
CGFloat red, green, blue, alpha;
[color getRed:&red green:&green blue:&blue alpha:&alpha];
integer += ((int)(alpha * 255) & 0xff) << 24;
integer += ((int)(red * 255) & 0xff) << 16;
integer += ((int)(green * 255) & 0xff) << 8;
integer += ((int)(blue * 255) & 0xff);
return [NSNumber numberWithInteger:integer];
}


But then I keep getting the error in the question:


Swift Version


class func serialize(color: UIColor) {
var integer: UInt32 = 0;
var red: CGFloat, green:CGFloat, blue: CGFloat, alpha: CGFloat
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

integer += (Int((alpha * 255) & 0xff)
integer += (Int((red * 255)) & 0xff) << 16
integer += (Int((green * 255)) & 0xff) << 8
integer += (Int((blue * 255)) & 0xff)

Answer

You need to initialize your vars red, green, blue and alpha before passing them to getRed method. Integer is UInt32 type so you need to coerce all the CGFloats to UInt32 before adding it up to integer or make it an Int. I would do it as follow:

extension UIColor  {
    var hexa: Int {
        var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
        getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        return Int(alpha * 255) << 24
             + Int(red   * 255) << 16
             + Int(green * 255) << 8
             + Int(blue  * 255)
    }
}

The other way:

extension UIColor{
    convenience init(hexa: Int) {
        self.init(red:   CGFloat((hexa & 0xFF0000)   >> 16)/255,
                  green: CGFloat((hexa & 0xFF00)     >> 8 )/255,
                  blue:  CGFloat((hexa & 0xFF)            )/255,
                  alpha: CGFloat((hexa & 0xFF000000) >> 24)/255)
    }
}

Testing

UIColor(hexa: UIColor.green().hexa)   // r 0.0 g 1.0 b 0.0 a 1.0