Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extensions May not contain Stored properties

Can I implement this in Swift with Extensions without the need to inheritance?. I get this error Extensions May not contain Stored properties

extension UIButton {     @IBInspectable var borderWidth : CGFloat         {         didSet{             layer.borderWidth = borderWidth         }     }  } 
like image 815
Mohamed DiaaEldin Avatar asked Mar 31 '16 15:03

Mohamed DiaaEldin


People also ask

Can extension have stored properties?

As you may know Swift does not allow stored properties into extensions. That's by design: “Extensions may not contain stored properties.”

Why extensions may not contain stored properties?

error: extensions may not contain stored properties . It means that Swift doesn't support stored properties inside the extension. Therefore, we cannot use the toggleState property to keep the internal state of our toggle button. For this reason, we need a workaround.

Can we declare properties in extensions Swift?

(Unlike Objective-C categories, Swift extensions don't have names.) Extensions in Swift can: Add computed instance properties and computed type properties.

Can we create stored property in protocol?

It seems you want to add a stored property to a type via protocol extension. However this is not possible because with extensions you cannot add a stored property.


2 Answers

You can override the setter/getter so that it isn't a stored property and just forwards the set/get to the layer.

extension UIButton {     @IBInspectable var borderWidth : CGFloat {         set {             layer.borderWidth = newValue         }          get {             return layer.borderWidth         }     } } 
like image 80
dan Avatar answered Sep 28 '22 04:09

dan


Extensions cannot add stored properties. From the docs (Computed Properties section):

Note

Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.

If you have a need for stored properties, you should create a subclass, like so:

class CustomButton : UIButton {     @IBInspectable var borderWidth : CGFloat         {         didSet{             layer.borderWidth = borderWidth         }     }  } 
like image 45
Alexander Avatar answered Sep 28 '22 03:09

Alexander