0

A perfect example of calling a method without initialising the class in Swift is for UIColor.

You can do UIColor.whiteColor(). Notice how the () is at the end of whiteColor.

If I were to extend UIColor for a custom method:

extension UIColor {
    /** Set the color to white. */
    func white() -> UIColor {
        return UIColor.whiteColor()
    }
}

I would have to call this method like so: UIColor().white() instead of like this UIColor.white().

How can I write methods where the initialiser is only at the end? Or is this only available when the class is written in Objective-C?

Josh
  • 745
  • 1
  • 7
  • 22

1 Answers1

3

You need to make the function either a class or static function. For example:

extension UIColor {
    /** Set the color to white. */
    class func white() -> UIColor {
        return UIColor.whiteColor()
    }
}

You can also use the word static instead of class.

AdamPro13
  • 7,232
  • 2
  • 30
  • 28