我正在编写一个小应用程序,我需要将一个变量传递给一个函数。问题是该变量是一个绑定(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/