gpt4 book ai didi

swiftui - 如何修复无法将类型 'Binding' 的值转换为预期的参数类型 'Device'

转载 作者:行者123 更新时间:2023-12-01 23:14:59 30 4
gpt4 key购买 nike

我正在编写一个小应用程序,我需要将一个变量传递给一个函数。问题是该变量是一个绑定(bind),但该函数必须接受一个常规变量。

代码:

ForEach($deviceArrays.devices, id: \.id) { deviceArray in
HStack {
ForEach(deviceArray.row, id: \.id) { device in
AnotherView(device: $currentDevice, size: $size)
.onAppear {
setCurrentDevice(to: device)
}
}
}
}
func setCurrentDevice(to device: Device) {
currentDevice = device
}

最佳答案

这里的问题是在这一行:

ForEach($deviceArrays.devices, id: \.id) { deviceArray in

你应该使用 $deviceArray相反,因为您输入的是 Binding进入ForEach .然后你可以访问deviceArray为常规值。


其他解决方案

使用它的 wrappedValue属性(property)。

这会转换 Binding<T> 的类型至 T .在你的情况下,Binding<Device>Device .

ForEach($deviceArrays.devices, id: \.id) { deviceArray in
HStack {
ForEach(deviceArray.row, id: \.id) { device in
AnotherView(device: $currentDevice, size: $size)
.onAppear {
setCurrentDevice(to: device.wrappedValue)
}
}
}
}

关于swiftui - 如何修复无法将类型 'Binding<Device>' 的值转换为预期的参数类型 'Device',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69106886/

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