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

How to fix Cannot convert value of type 'Binding<Device>' to expected argument type '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)
                    }
        }
    }
}
func setCurrentDevice(to device: Device) {
    currentDevice = device
}

这里的问题是在这一行:

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

您应该使用 $deviceArray,因为您正在将 Binding 输入到 ForEach。然后您可以访问 deviceArray 以获得常规值。


其他解决方案

使用其 wrappedValue 属性.

这会将 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)
                    }
        }
    }
}

我的解决方案:

双榜

注意:CalcButton 是枚举:String

 let buttons: [[CalcButton]] = [
    [.clear, .negative, .percent, .divide],
    [.seven, .eight, .nine, .mutliply],
    [.four, .five, .six, .subtract],
    [.one, .two, .three, .add],
    [.zero, .decimal, .equal],
]

循环示例:

  // Our buttons
            ForEach(buttons, id: \.self) { row in
                HStack(spacing: 12) {
                    ForEach(row, id: \.self) { item in
                        Button(action: {
                            
                            self.didTap(button: item)
                            
                        }, label: {
                            Text(item.rawValue)
                                .font(.system(size: 32))
                                .bold()
                                .frame(
                                    width: self.buttonWidth(item: item),
                                    height: self.buttonHeight()
                                )
                                .background(item.buttonColor)
                                .foregroundColor(.white)
                                .cornerRadius(self.buttonWidth(item: item)/2)
                        })
                    }
                }
                .padding(.bottom, 3)
            }
        }

谢谢!