啊!你好亲近 这就是你的做法。您错过了美元符号(测试版3)或下划线(测试版4),并且在您的amount属性前面输入了self,或者在amount参数之后输入了.value。所有这些选项均有效:
您会看到我删除了@State
includeDecimal中的内容,请检查最后的说明。
这是使用属性(将self放在其前面):
struct AmountView : View {
@Binding var amount: Double
private var includeDecimal = false
init(amount: Binding<Double>) {
self._amount = amount
self.includeDecimal = round(self.amount)-self.amount > 0
}
}
或之后使用.value(但不使用self,因为您使用的是传递的参数,而不是struct的属性):
struct AmountView : View {
@Binding var amount: Double
private var includeDecimal = false
init(amount: Binding<Double>) {
self._amount = amount
self.includeDecimal = round(amount.value)-amount.value > 0
}
}
相同,但是我们对参数(withAmount)和属性(amount)使用不同的名称,因此您可以清楚地看到使用它们的时间。
struct AmountView : View {
@Binding var amount: Double
private var includeDecimal = false
init(withAmount: Binding<Double>) {
self._amount = withAmount
self.includeDecimal = round(self.amount)-self.amount > 0
}
}
struct AmountView : View {
@Binding var amount: Double
private var includeDecimal = false
init(withAmount: Binding<Double>) {
self._amount = withAmount
self.includeDecimal = round(withAmount.value)-withAmount.value > 0
}
}
请注意,由于属性包装器(@Binding)会创建不需要该.value的访问器,因此属性不需要.value。但是,有了参数,就没有这种事情了,您必须显式地执行它。如果您想了解有关属性包装器的更多信息,请查看WWDC会话415-Modern Swift API Design并跳至23:12。
如您所见,从初始化程序修改@State变量将引发以下错误:线程1:致命错误:在View.body之外访问State。为了避免这种情况,您应该删除@State。这是有道理的,因为includeDecimal不是事实的来源。其值是从金额中得出的。但是,通过删除@StateincludeDecimal
不会在金额更改时更新。为此,最好的选择是将includeDecimal定义为计算属性,以便其值源自真值(量)。这样,每当金额更改时,您的includeDecimal也会更改。如果您的视图依赖于includeDecimal,则它应在更改时更新:
struct AmountView : View {
@Binding var amount: Double
private var includeDecimal: Bool {
return round(amount)-amount > 0
}
init(withAmount: Binding<Double>) {
self.$amount = withAmount
}
var body: some View { ... }
}
如rob mayoff所示,您还可以使用$$varName
(beta 3)或_varName
(beta4)初始化State变量:
$$includeDecimal = State(initialValue: (round(amount.value) - amount.value) != 0)
_includeDecimal = State(initialValue: (round(amount.value) - amount.value) != 0)
self.includeDecimal = round(self.amount)-self.amount > 0
的Thread 1: Fatal error: Accessing State<Bool> outside View.body