Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    }
}
like image 803
Josh Avatar asked Sep 23 '16 10:09

Josh


2 Answers

You can use computed properties:

extension UIColor {
    static var custom: UIColor {
        return UIColor(white: 0.5, alpha: 1)
    }
}
like image 145
FelixSFD Avatar answered Oct 03 '22 01:10

FelixSFD


.whiteColor() is a static method (type method) on UIColor, whereas .white is a static (computed in my example) property on UIColor. The difference in defining them looks like:

struct Color {
  let red: Int
  let green: Int
  let blue: Int

  static func whiteColor() -> Color {
    return Color(red: 255, green: 255, blue: 255)
  }

  static var white: Color {
    return Color(red: 255, green: 255, blue: 255)
  }
}
like image 33
mAu Avatar answered Oct 03 '22 02:10

mAu