问题
When I try and assign the output of the Toggle to an old variable it says: Binding is not convertible to bool. Is there a way to fix this. I am coding this in Swift Playgrounds. The code below is the part which doesn't function
import SwiftUI
import PlaygroundSupport
struct ContentView : View {
@State private var redButton = false
@State private var step = 0
@State private var washingHandsToggle = true
@State private var wearingMaskToggle = true
@State private var coverMouthToggle = true
@State private var quarantineToggle = true
@State private var text = ""
@State private var slide = 20.0
@State private var slidetwo = 500000.0
@State private var r0 = 0
@State private var rvalues = [6.5, 6.1, 5.3, 4.8, 4.2, 3.5, 3.1, 2.9, 1.75, 1.5, 1.2, 1.0, 0.92, 0.82, 0.75, 0.7]
var body: some View {
VStack {
VStack {
Toggle(isOn: $washingHandsToggle) {
Text("Washing Hands Regularly")
}.padding(.horizontal, 50)
.padding(.vertical, 25)
Toggle(isOn: $wearingMaskToggle) {
Text("Wearing a Protective Mask")
}.padding(.horizontal, 50)
.padding(.vertical, 25)
Toggle(isOn: $coverMouthToggle) {
Text("Cover Mouth When Sneezing")
}.padding(.horizontal, 50)
.padding(.vertical, 25)
Toggle(isOn: $quarantineToggle) {
Text("Quarantine")
}.padding(.horizontal, 50)
.padding(.vertical, 25)
.padding(.bottom, 30)
r0 = rvalues[(wearingMaskToggle ? 1:0) + (washingHandsToggle ? 2:0) + (quarantineToggle ? 8:0) + (coverMouthToggle ? 4:0)]
if !washingHandsToggle && !wearingMaskToggle && !quarantineToggle {
Text("Select At least 1")
}else {
Text("Your R") + Text("0")
.font(.system(size: 15.0))
.baselineOffset(-6.0) + Text("Value Is")
Text("\(r0)")
}
回答1:
You can't just set r0
in the middle of a VStack
. In general, it becomes very messy if you start writing normal statements like assignment, loops, method calls, in a function builder, like the closure argument to VStack.init
.
You'd better make r0
a computed property:
var r0 : Double {
rvalues[(wearingMaskToggle ? 1:0) + (washingHandsToggle ? 2:0) + (quarantineToggle ? 8:0) + (coverMouthToggle ? 4:0)]
}
And delete the line where you set r0
.
One of the four Text
s in the else
branch is missing a +
. You should write:
Text("Your R") +
Text("0 ")
.font(.system(size: 15.0))
.baselineOffset(-6.0) +
Text("Value Is ") +
Text("\(r0)")
Also, I noticed you did not include coverMouthToggle
in the if statement. That might be a typo...
来源:https://stackoverflow.com/questions/61714040/when-i-try-and-assign-the-output-of-the-toggle-to-an-old-variable-it-says-bindi