Extensions must not contain stored properties
Seen this error ? I bet yes if you have done any basic Swift coding at all.
Ever wondered why Swift compiler complains about this, or you just didn't care as long as you can move the property back to the class itself from the extension and be done with it ? Yes, that is one way to do it, but not the best way to do it.
The following code (also given in the above image) will surely throw the error at your face.
protocol ProtocolWithSyntaxErrors {
func canHandleError -> Bool
var errors: [String] { get }
}
And then the class you want
class ClassWithSyntaxErrors { }
Now you want to implement the protocol, the best practice is to use an extension
extension ClassWithSyntaxErrors : ProtocolWithSyntaxErrors {
var errors: [String] = [] // This is where it will say Extensions must not contain stored properties
func canHandleError() -> Bool {
return false
}
}
Swift is been reasonable here, because if you are using a stored property inside the extension which you cannot directly initialize through a constructor, it could be a problem for the Swift.
One way to get rid of this error is to add setter and getters to make it not a Stored property, such as below.
var errors: [String] {
set {
_ = newValue
}
get {
["Extensions must not contain stored properties"]
}
}
But here you are just overriding the getters and setters so that you can go around the Swift compiler. Even though this example is not a practical one, let me put out a practical example you may have to use.
Take a look at if you have to extend a given UIKit class, say UITextField
extension UITextField {
@IBInspectable var borderWidth : CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
}
What you are doing is that, you override the getter and setter and passing the get and set to the layer property. Hope that helps someone. Going forward, I will stick to a small topic like this. It could be a syntax error, design problem or any other issue you face day in and day out. Please don't be shy to let me know what you think.
Add new comment