Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do you put a global method in swift?

Tags:

ios

swift

I have a function that is common to all my controllers:

func myColor() -> UIColor {
    return UIColor(red: 9.0/255.0, green: 134.0/255.0, blue: 255.0/255.0, alpha: 1)
}

Where can I put this function, so I can access it from any controller?


1 Answers

By default all default access scope (internal) functions are available everywhere in the application. If you have this function defined in different module, you need to use public modifier.

To make your code clearer it is best to create extension for UIColor.

extension UIColor {
    class func myColor() -> UIColor {
        return UIColor(red: 9.0/255.0, green: 134.0/255.0, blue: 255.0/255.0, alpha: 1)
    }
}

Then you can use myColor same way as default UIColor colors.

let systemColor = UIColor.blackColor()
let myColor = UIColor.myColor()
like image 161
Kirsteins Avatar answered Feb 04 '26 17:02

Kirsteins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!