此代码在BigSur 11.2.3上的Xcode 12.5操场上M1 mac上工作:
import UIKit
var Choice = Array(repeating: "" , count: 3)
Choice [0] = """
This is the land of Gaul
The people are tall
and the children are small
"""
Choice [1] = """
This is the land of Anglos
The people wear black clothes
and they never eat mangoes
"""
Choice [2] = """
This is the land of Hesperia
The people drink their vangueria
and never suffer hysteria
"""
print(Choice [1])但是,当它在swiftUI视图中时,如下所示:
import SwiftUI
struct ThirdCalcView: View {
@State private var selectedChoice = 0
var str1 = """
This goes
over multiple
lines
"""
var Choice = Array(repeating: "" , count: 3)
Choice [0] = """
This is the land of Gaul
The people are tall
and the children are small
"""
Choice [1] = """
This is the land of Anglos
The people wear black clothes
and they never eat mangoes
"""
Choice [2] = """
This is the land of Hesperia
The people drink their vangueria
and never suffer hysteria
"""
var body: some View {
Form {
Section {
Picker("Choice", selection: $selectedChoice, content: {
Text("France").tag(0)
Text("England").tag(1)
Text("Spain").tag(2)
})
}//section
Section {
Text("The mnemonic is:\(Choice[selectedChoice])")
}//section
} //form
}//some view
} //ThirdCalcView
struct ThirdCalcView_Previews: PreviewProvider {
static var previews: some View {
ThirdCalcView()
}
}在“var抉择”声明之后,我得到了以下一系列错误:

我注释了结束大括号,以确保我没有错数。
开始时简单的'str1‘多行声明很好,所以我认为我对数组的声明导致了这个问题。
我想根据用户的选择显示一个字符串。最终,在应用程序中,用户必须在显示响应之前做出三个选择,所以我想使用一个三维数组。
发布于 2021-05-03 21:10:40
您不能在Choice[0] = ...或struct的顶层编写这样的代码(意为class )--它必须位于函数或初始化器的内部。
你有几个选择。最简单的方法就是在创建时声明Choice,而不是强制分配每个索引:
struct ThirdCalcView: View {
@State private var selectedChoice = 0
let Choice = [
"""
This is the land of Gaul
The people are tall
and the children are small
""",
"""
This is the land of Anglos
The people wear black clothes
and they never eat mangoes
""",
"""
This is the land of Hesperia
The people drink their vangueria
and never suffer hysteria
"""]
var body: some View {
//...
}
}(注:通常情况下,变量名在Swift中是小写的)
另一个选项是从开关语句返回String:
struct ThirdCalcView: View {
@State private var selectedChoice = 0
func mnemonic() -> String {
switch selectedChoice {
case 0:
return """
This is the land of Gaul
The people are tall
and the children are small
"""
case 1:
return """
This is the land of Anglos
The people wear black clothes
and they never eat mangoes
"""
case 2:
return """
This is the land of Hesperia
The people drink their vangueria
and never suffer hysteria
"""
default:
assertionFailure("Shouldn't reach here")
return ""
}
}
var body: some View {
Form {
Section {
Picker("Choice", selection: $selectedChoice) {
Text("France").tag(0)
Text("England").tag(1)
Text("Spain").tag(2)
}
}//section
Section {
Text("The mnemonic is:\(mnemonic())")
}//section
} //form
}//some view
} //ThirdCalcView您可以进一步重构它,以便根据带有国家名称的enum进行选择,然后根据枚举值返回不同的助记符。
https://stackoverflow.com/questions/67375764
复制相似问题