'How to fix Cannot convert value of type 'Binding<Device>' to expected argument type 'Device'
I am coding up a little app and I need to pass a variable to a function. The problem is that that variable is a binding but the function has to accept a regular variable.
Code:
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
}
Solution 1:[1]
The problem here is that on this line:
ForEach($deviceArrays.devices, id: \.id) { deviceArray in
You should use $deviceArray instead, because you are inputting a Binding into the ForEach. Then you can access deviceArray for the regular value.
Other solution
Use its wrappedValue property.
This converts a type of Binding<T> to T. In your case, Binding<Device> to 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)
}
}
}
}
Solution 2:[2]
My Solution:
Double List
Note: CalcButton is Enum: String
let buttons: [[CalcButton]] = [
[.clear, .negative, .percent, .divide],
[.seven, .eight, .nine, .mutliply],
[.four, .five, .six, .subtract],
[.one, .two, .three, .add],
[.zero, .decimal, .equal],
]
Loop Example:
// 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)
}
}
Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Mr. Tayyab MuGhal |
