简体   繁体   中英

Swift: Default Initializer for Computed Property

It seems like I can't give a computed property a default value using the Default Initializers method that can be used for Stored Properties. Here's a use case where I would need this:

@IBDesignable public class MyRoundedCornersView: UIView {

    @IBInspectable var cornerRadius: CGFloat {
        get {
            return self.layer.cornerRadius
        }
        set {
            self.layer.cornerRadius = newValue
        }
    }

}

I'd like to give the cornerRadius a default value. But the following doesn't 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 the not so useful '(() -> () -> $T1) -> $T2' is not identical to 'Double' error. I looked up here to find out how to do this but it seems Apple doesn't support default values for computed properties. At least I couldn't find anything.

So how can I still make sure that I have a default value for my property? This thread says it isn't possible within the init method either – but even if, I'd like to keep the default value near my property definition. Does anyone have an idea?

It doesn't make sense to set a default value to a computed property because it doesn't have a proper value :

[...] computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

Maybe you want to set the default in the layer type, like :

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

Another solution is to use a stored property like this :

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

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

It's possible to init the 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 one can just provide a default value for the stored property b , and retrieve a from b .

The reason why computed property exists is that you can calculate(or update) something based on other properties, and directly use it through computed property.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM