gpt4 book ai didi

swift - 将 boolean 值更改为 Int

转载 作者:行者123 更新时间:2023-12-02 18:13:33 26 4
gpt4 key购买 nike

我正在寻求您的帮助来帮助我制作我的第一个应用程序。我白天是盲人和视障人士的老师,正在尝试制作一个应用程序用于对学生进行评估。在这个特定部分中,我们正在评估他们的位置/空间技能。我们喜欢使用切换的便利性,但我很难将 bool 值更改为 Int 以获得每个部分的分数。我希望 true = 1 和 false = 0。数字分数将列在每个部分下方,我已经将其编码出来。

我尝试使用“扩展”来更改值,但不断收到错误。我可以将它们全部更改为分段选择器,并获得接近相同的易用性,但希望有一个更简单的解决方案,因为我已经编写了大约 100 个这样的代码。提前致谢!

struct caneSkills: View {
@State var front = false
@State var behind = false
@State var onTop = false
@State var below = false
@State var between = false
@State var nextTo = false
@State var under = false
@State var onBottom = false
@State var inBack = false
@State var onTheSide = false
var body: some View {
let psScore = (front + behind + onTop + below + between + nextTo + under + onBottom + inBack + onTheSide)
NavigationView {
Form {
Section(header: Text("Positional/Spatial Concepts")) {
Toggle("Behind", isOn: $behind)
Toggle("Below", isOn: $below)
Toggle("In Back", isOn: $inBack)
Toggle("In Between", isOn: $between)
Toggle("In Front", isOn: $front)
Toggle("Next To", isOn: $nextTo)
Toggle("On The Bottom", isOn: $onBottom)
Toggle("On Side", isOn: $onTheSide)
Toggle("On Top", isOn: $onTop)
Group {
Toggle("Under", isOn: $under)
Text("Positional/Spatial Concepts Score: \(psScore) / 10")
.font(.headline)
.foregroundColor(Color.blue)
}
}
}
.navigationTitle("Cane Skills")
}
.navigationViewStyle(StackNavigationViewStyle())
}
}

最佳答案

只是为了好玩,您可以扩展 Bool 类型并向其添加值属性。然后,您可以简单地创建一个自定义运算符来对所有 bool 元素求和:

extension Bool {
var value: Int { self ? 1 : 0 }
public static func + (lhs: Int, rhs: Bool) -> Int {
lhs + rhs.value
}
}

我还会构建数据技能。这样你就可以拥有一个包含你所有技能的数组:

struct Skill {
let name: String
var isOn: Bool
}

struct CaneSkills: View {

@State var skills = [
("Behind", false),
("Below", false),
("In Back", false),
("In Between", false),
("In Front", false),
("Next To", false),
("On The Bottom", false),
("On Side", false),
("On Top", false),
("Under", false)
].map(Skill.init)

var body: some View {
NavigationView {
Form {
Section(header: Text("Positional/Spatial Concepts")) {
ForEach(skills.indices, id: \.self) { index in
Toggle(skills[index].name, isOn: $skills[index].isOn)
}
Text("Score: \(psScore) / 10")
.font(.headline)
.monospacedDigit()
.foregroundColor(Color.blue)
.frame(maxWidth: .infinity, alignment: .trailing) }
}
.navigationTitle("Cane Skills")
}
.navigationViewStyle(StackNavigationViewStyle())
}
}

extension CaneSkills {
var psScore: Int {
skills.reduce(0) { $0 + $1.isOn }
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
CaneSkills()
}
}

enter image description here

关于swift - 将 boolean 值更改为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71948486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com