gpt4 book ai didi

ios - Swift:计算属性的默认初始化器

转载 作者:搜寻专家 更新时间:2023-10-30 22:26:34 25 4
gpt4 key购买 nike

似乎我无法使用可用于存储属性的默认初始值设定项方法为计算属性提供默认值。这是我需要这个的用例:

@IBDesignable public class MyRoundedCornersView: UIView {

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

}

我想给 cornerRadius 一个默认值。但是以下不起作用(只是添加了 = 8.0):

@IBDesignable public class MyRoundedCornersView: UIView {

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

}

我得到了 not so useful '(() -> () -> $T1) -> $T2' is not identical to 'Double' 错误。我查了一下here了解如何执行此操作,但 Apple 似乎不支持计算属性的默认值。至少我找不到任何东西。

那么我怎样才能确保我的属性有一个默认值呢? This thread说这在 init 方法中也是不可能的——但即使如此,我还是希望将默认值保持在我的属性定义附近。有人有想法吗?

最佳答案

将默认值设置为 computed property 没有意义因为它没有合适的值:

[...] 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.

也许您想在图层类型中设置默认值,例如:

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

另一种解决方案是使用这样的存储属性:

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

编辑:这不能保证 layer.cornerRadius == self.cornerRadius,尤其是直接设置 layer.cornerRadius 时

关于ios - Swift:计算属性的默认初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25425644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com