[英]How can I solve Escaping closure captures 'inout' parameter in Swift?
我想用一個函數更新一個狀態值,在這個函數中我想使用一個DispatchQueue但我收到這個錯誤:
Escaping closure captures 'inout' parameter 'currentValue'
我該如何解決這個問題?
struct ContentView: View {
@State private var offset: CGFloat = CGFloat()
var body: some View {
Color.yellow
.overlay(
Circle()
.fill(Color.red)
.frame(width: 100.0, height: 100.0, alignment: .center)
.offset(y: offset)
)
.overlay(
Button("update") {
updater(currentValue: &offset, goalValue: 300.0)
}
.font(Font.body.bold())
.padding()
, alignment: .bottom)
}
}
func updater(currentValue: inout CGFloat, goalValue: CGFloat) {
if (currentValue + 1.0) <= goalValue {
currentValue += 1.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1000)) {
updater(currentValue: ¤tValue, goalValue: goalValue)
}
}
}
您可以通過創建一個額外的變量來修復您的錯誤。 像這樣
func updater(currentValue: inout CGFloat, goalValue: CGFloat) {
var currentValue = currentValue // <--- Here
if (currentValue + 1.0) <= goalValue {
currentValue += 1.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1000)) {
updater(currentValue: ¤tValue, goalValue: goalValue)
}
}
}
但是通過這樣做,您的視圖無法更新。 您可以通過此修改您的代碼
struct ContentView: View {
@State private var offset: CGFloat = CGFloat()
var body: some View {
Color.yellow
.overlay(
Circle()
.fill(Color.red)
.frame(width: 100.0, height: 100.0, alignment: .center)
.offset(y: offset)
)
.overlay(
Button("update") {
updater(goalValue: 300.0)
}
.font(Font.body.bold())
.padding()
, alignment: .bottom)
}
func updater(goalValue: CGFloat) {
if (offset + 1.0) <= goalValue {
offset += 1.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1000)) {
updater(goalValue: goalValue)
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.