当我尝试将 Toggle 的输出分配给旧变量时,它说: Binding<Bool>不可转换为 <Bool> [英] When I try and assign the output of the Toggle to an old variable it says: Binding<Bool> is not convertible to <Bool>
问题描述
当我尝试将 Toggle 的输出分配给旧变量时,它说:绑定不能转换为 bool.有没有办法来解决这个问题.我正在 Swift Playgrounds 中编写此代码.下面的代码是不起作用的部分
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)")
}
推荐答案
你不能只在 VStack
的中间设置 r0
.通常,如果您开始在函数构建器中编写普通语句(例如赋值、循环、方法调用),例如 VStack.init
的闭包参数,则会变得非常混乱.
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
.
你最好让 r0
成为一个计算属性:
You'd better make r0
a computed property:
var r0 : Double {
rvalues[(wearingMaskToggle ? 1:0) + (washingHandsToggle ? 2:0) + (quarantineToggle ? 8:0) + (coverMouthToggle ? 4:0)]
}
并删除您设置 r0
的行.
And delete the line where you set r0
.
else
分支中的四个 Text
之一缺少 +
.你应该写:
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)")
另外,我注意到您没有在 if 语句中包含 coverMouthToggle
.这可能是一个错字...
Also, I noticed you did not include coverMouthToggle
in the if statement. That might be a typo...
这篇关于当我尝试将 Toggle 的输出分配给旧变量时,它说: Binding<Bool>不可转换为 <Bool>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!