Swift: default initializer for computed property

It seems like I cannot give the computed property a default value using the Initial Initializers method, which can be used for stored properties. Here, the case is used when I need it:

@IBDesignable public class MyRoundedCornersView: UIView { @IBInspectable var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.cornerRadius = newValue } } } 

I would like to give cornerRadius a default value. But the following does not work (just added = 8.0 ):

 @IBDesignable public class MyRoundedCornersView: UIView { @IBInspectable var cornerRadius: CGFloat = 8.0 { get { return self.layer.cornerRadius } set { self.layer.cornerRadius = newValue } } } 

I get a not very useful error '(() -> () -> $T1) -> $T2' is not identical to 'Double' . I looked here to find out how to do this, but Apple doesn't seem to support the default values ​​for computed properties. At least I could not find anything.

So, how can I make sure that I have a default value for my property? This thread says this is not possible in the init method, but even if I wanted to keep the default value next to my property definition. Does anyone have an idea?

+3
source share
2 answers

It does not make sense to set a default value for the computed property , because it does not have the correct value:

[...] computed properties that do not actually store the value. Instead, they provide a getter and an additional installer to retrieve and set other properties and values ​​indirectly.

Perhaps you want to set the default value in the layer type, for example:

 class Layer { // <- The type of layer var cornerRadius: CGFloat = 8.0 // ... } 

Another solution is to use a stored property as follows:

 var cornerRadius:CGFloat = 8.0 { didSet { self.layer.cornerRadius = self.cornerRadius } } 

Edit: this does not guarantee that layer.cornerRadius == self.cornerRadius, especially if layer.cornerRadius is set directly

+6
source

It is possible to initialize a computed property in init like this.

 class TestProperty { var b = 0 var a: Int { get { return b + 1 } set { b = newValue - 1 } } init(a: Int) { self.a = a } } 

But you can simply specify the default value for the saved property b and extract a from b .

The reason that a computed property exists is because you can compute (or update) something based on other properties and use it directly through the computed property.

I wonder why you would like to provide a default value for computed properties.

+3
source

All Articles