Extensions and stored properties

Greetings, my friends!

In chapter 17, in the “Extensions” section, we read and remember that stored properties cannot be added to extensions. Ok.

With extensions, you can add methods and computed properties (but not stored properties) to types.

But further, extanding the UIColor type, don’t we add stored properties in this code? It’s not like computed properties, is it?

extension UIColor {
    static let angry = UIColor(named: "angryRed")!
    static let confused = UIColor(named: "confusedPurple")!
    static let crying = UIColor(named: "cryingLightBlue")!
    static let goofy = UIColor(named: "goofyOrange")!
    static let happy = UIColor(named: "happyTurquoise")!
    static let meh = UIColor(named: "mehGray")!
    static let sad = UIColor(named: "sadBlue")!
    static let sleepy = UIColor(named: "sleepyLightRed")!
}
1 Like

This works because the attributes are static, which means that there is only one copy of these properties owned by the UIColor type which are shared by all variables of that type. They don’t require adding any storage to UIColor variables, so it’s allowed. Remove the static keyword and it won’t compile.

2 Likes

Thanks for the explanation! :slightly_smiling_face:

This is possible because the attributes are static. This means that these properties are only present in one instance of the UIColor type and that all variables of the same type share them.