Cody Weaver Cody Weaver - 6 months ago 19
Swift Question

Swift omit class on initalization

I am trying to create custom properties in Swift that allow me to omit the base class. Something like what is allowed with the base colors within

UIColor
.

self.backgroundColor = .blueColor()


I know that works but I want to add my own custom colors. I would like the syntax to be something like:

self.backgroundColor = .customColor()

Answer

You can simply write an extension for UIColor in order to do this. For example:

extension UIColor {

    // your custom color function
    class func customColor() -> UIColor {
        return UIColor(red: 0.3, green: 0.4, blue: 0.5, alpha: 0.6)
    }
}


...

self.backgroundColor = .customColor()

Although I had no idea that convenience syntax was in the language... thought it was only for enums. So thanks for showing me that!

Comments