Josh Josh - 4 months ago 9
iOS Question

iOS - How to call a method without initialising the class in Swift?

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?

Answer

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.

Comments