Swift:计算属性的默认初始化程序 [英] Swift: Default Initializer for Computed Property
问题描述
似乎我无法使用可用于存储属性的Default Initializers方法为计算属性提供默认值。这是一个用例,我需要这个:
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
}
}
}
我想给cornerRadius是一个默认值。但以下不起作用(只需添加 = 8.0
):
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
}
}
}
我得到的不太有用'(() - >() - > $ T1) - > $ T2'与'Double'
错误不同。我查了一下这里以了解如何执行此操作,但Apple似乎不支持计算属性的默认值。至少我找不到任何东西。
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.
那么我怎样才能确保我的财产有默认值? 此主题表示在init方法中无法实现要么 - 但即使我想保持默认值接近我的属性定义。有没有人有想法?
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 :
[...]计算属性,它们实际上并不存储值。相反,它们提供了一个getter和一个可选的setter来间接检索和设置其他属性和值。
[...] 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
}
}
编辑:这不保证layer.cornerRadius == self.cornerRadius,特别是如果直接设置了layer.cornerRadius
This does not guarantee that layer.cornerRadius == self.cornerRadius, especially if the layer.cornerRadius is set directly
这篇关于Swift:计算属性的默认初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!