[英]Changing a optional property value with the use of a default initializer in Swift 3
[英]Swift: Default Initializer for Computed Property
我似乎無法使用可用於存儲屬性的Default Initializers方法為計算屬性提供默認值。 這是一個用例,我需要這個:
@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
}
}
}
我得到了不太有用的'(() -> () -> $T1) -> $T2' is not identical to 'Double'
錯誤不同。 我在這里查找了如何做到這一點,但似乎Apple不支持計算屬性的默認值。 至少我找不到任何東西。
那么我怎樣才能確保我的屬性有默認值? 這個線程說在init方法中也不可能 - 但即使我想在我的屬性定義附近保留默認值。 有沒有人有想法?
將默認值設置為計算屬性沒有意義,因為它沒有正確的值:
[...]計算屬性,實際上不存儲值。 相反,它們提供了一個getter和一個可選的setter來間接檢索和設置其他屬性和值。
也許你想在圖層類型中設置默認值,例如:
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
這是可能的初始化計算的財產init
,像這樣。
class TestProperty {
var b = 0
var a: Int {
get {
return b + 1
}
set {
b = newValue - 1
}
}
init(a: Int) {
self.a = a
}
}
但是,一個可以只提供存儲屬性的默認值b
,並獲取a
從b
。
存在計算屬性的原因是您可以基於其他屬性計算(或更新)某些內容,並直接通過計算屬性使用它。
我想知道你為什么要為計算屬性提供默認值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.