Arbitur
Arbitur

Reputation: 39081

UIColor extension in Swift error

I have this extension:

extension UIColor {
    func rgba(r: Int, g: Int, b: Int, a: Float) -> UIColor {
        return UIColor(red: r/255, green: g/255, blue: b/255, alpha: a)
    }    
}

This is giving me an error message: Extra argument 'green' in call

I dont get why this is happening, might be a bug in xcode 6 beta 4 or in swift.

Upvotes: 3

Views: 4248

Answers (3)

Alex
Alex

Reputation: 7057

Try this:

extension UIColor {
    class func rgba(r: Int, g: Int, b: Int, a: Float) -> UIColor {
        return UIColor(red: r/255, green: g/255, blue: b/255, alpha: a)
    }     
}

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236275

extension UIColor {
    convenience init(r: Int, g:Int , b:Int , a: Int) {
        self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: CGFloat(a)/255)
    }
}
let myColor = UIColor(r: 255 , g: 255, b: 255, a: 255)

Upvotes: 3

Louis Zhu
Louis Zhu

Reputation: 802

It is because you passed all the parameters with wrong type: r/255, g/255, b/255 are Integer and a is Float, but the UIColor's init method accepts CGFloat for the 4 parameters.

Modify the code to:

func rgba(r: Int, g: Int, b: Int, a: Float) -> UIColor {
    let floatRed = CGFloat(r) / 255.0
    let floatGreen = CGFloat(g) / 255.0
    let floatBlue = CGFloat(b) / 255.0
    return UIColor(red: floatRed, green: floatGreen, blue: floatBlue, alpha: CGFloat(a))
}

Upvotes: 8

Related Questions