[英]Please help: Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
I am trying to write code containing an If statement which depends on the responses entered by user for a series of questions.我正在尝试编写包含 If 语句的代码,该语句取决于用户输入的一系列问题的响应。 Different responses will add different values to variable "Score".不同的响应将为变量“Score”添加不同的值。 My code is fairly simple, but I cannot figure why the error message "Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols" keeps popping up around my If statement.我的代码相当简单,但我不明白为什么错误消息“类型'()'不能符合'视图';只有结构/枚举/类类型可以符合协议”在我的 If 语句周围不断弹出。 The If statement is at the very end. If 语句位于最后。 Thank you to anyone who is willing to help!感谢任何愿意提供帮助的人!
import SwiftUI
struct InfluenceLevel: View {
@State private var name = ""
@State private var age = "0"
@State private var gender = ""
@State private var nationality = ""
@State private var Instagram = ""
@State private var Celebrities = ""
@State private var Time = ""
@State private var products = ""
@State private var score = 0
var body: some View {
VStack {
Text("Please fill out the following questions to the best of your ability, allowing us to assess your susceptibility to advertising on social media")
Form{
Group{
Text("What is your gender? \(gender)" )
TextField("(Male/Female/Other):", text: $gender)
Text("Are you Chinese? \(nationality)" )
TextField("(Yes/No):", text: $nationality)
Text("Do you use Instagram? \(Instagram)" )
TextField("(Yes/No):", text: $Instagram)
}
Group{
Text("Do you mainly follow celebrities on social media? \(Celebrities)" )
TextField("(Yes/No):", text: $Celebrities)
Text("Do you spend less than an hour on social media every day? \(Time)" )
TextField("(Yes/No)", text: $Time)
Text("Do you use more than half of your monthly expenditure on stuff seen online? \(products)" )
TextField("(Yes/No)", text: $products)
}
}
}
.navigationBarTitle("Level of Influence")
if gender == "Male" {
score = score + 1
}
}
}
struct InfluenceLevel_Previews: PreviewProvider {
static var previews: some View {
InfluenceLevel()
}
}
Try this:尝试这个:
enum GenderEnum: Int {
case female, male, other
init(str: String) {
switch str {
case "Male":
self = .male
case "Female":
self = .female
default:
self = .other
}
}
}
struct InfluenceLevel: View {
@State private var gender = ""
@State private var score = 0
var body: some View {
let binding = Binding<String>(get: {
self.gender
}, set: {
self.gender = $0
score = GenderEnum(str: $0).rawValue
print(score)
})
VStack {
Text("Please fill out the following questions to the best of your ability, allowing us to assess your susceptibility to advertising on social media")
Form{
Group{
Text("What is your gender? \(gender)" )
TextField("(Male/Female/Other):", text: binding)
}
}
.navigationBarTitle("Level of Influence")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.