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 } } }
As you may know Swift does not allow stored properties into extensions. That's by design: “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.
(Unlike Objective-C categories, Swift extensions don't have names.) Extensions in Swift can: Add computed instance properties and computed type properties.
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.
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 } } }
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 } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With