Josh Josh - 2 months ago 12
Swift Question

Swift 3 - How to write functions with no initialisers like the new UIColors?

In previous versions of swift, you would get the colour white like this

UIColor.whiteColor()


However, in Swift 3, you get the colour white without initialisers like so
UIColor.white


How would I write this same function without having to use initialisers, as
UIColor.custom
?

extension UIColor {
func custom() {
return UIColor(white: 0.5, alpha: 1)
}
}

Answer

You can use computed properties:

extension UIColor {
    static var custom: UIColor {
        return UIColor(white: 0.5, alpha: 1)
    }
}