0

Say I have many functions that return more than one UIColor. Let's take a look at one of them:

func deepSkyBlue() -> UIColor {
    return UIColor(red: 0, green: 0.69, blue: 0.98, alpha: 1)
}

All my functions have alpha equal to 1.0, so it'd make sense to use an extension and omit one argument entirely. How can I do this?

4
  • What is the compiler error? Commented May 10, 2015 at 12:51
  • Missing argument for parameter 'alpha' in call. In fact, I still have to find a way to implement the neverAlpha code into my UIColor functions. Thanks! Commented May 10, 2015 at 12:52
  • So the compiler error is not for neverAlpha, but is for deepSkyBlue? Commented May 10, 2015 at 12:54
  • 1
    I've posted an answer for you, so perhaps stop editing your question for a second and see if that works for you? Commented May 10, 2015 at 13:00

1 Answer 1

4

If we want our alpha to be assumed as 1.0 when we don't pass it to the UIColor constructor, all we need to do is add a new constructor in an extension.

extension UIColor {
    convenience init(red: CGFloat, green: CGFloat, blue: CGFloat) {
        self.init(red: red, green: green, blue: blue, alpha: 1.0)
    }
}

And now we can use the three argument constructor you tried using:

static func deepSkyBlue() -> UIColor {
    return UIColor(red: 0, green: 0.69, blue: 0.98)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.