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

标签 swiftui binding

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

相关文章:

wpf - Bing map - 图钉的自动更新位置绑定(bind)

swift - 可以通过其结构的方法更改@State 属性的值吗?

ios - 如何在swiftui中使用内部选择器中的切换以及如何基于切换来更改选择器值

c# - 如何在 WPF 中将自定义对象绑定(bind)到列表框

binding - IBM MQ : Multiple QMs in JMS bindings file

wpf - MyContainer 派生自 FrameworkElement,具有绑定(bind)支持

class - 在 SwiftUI 中将一个 View 的一个 StateObject 类传递给另一 View 的另一个 StateObject 类

swiftUI - 强制屏幕横向后无法关闭模式屏幕

swift - 如何创建一个 View ,该 View 接受一个 Binding 并将其传递给 View 中的另一个 Binding - SwiftUI

angular - 向 Angular router.navigate 添加参数