我遇到的问题标题中提到了错误,但我不知道为什么或如何解决?从这里开始Swift爱好者,所以请以易于理解的术语进行解释。非常感谢。
struct Student {
let firstName: String
let lastName: String
let grade: String
}
struct Classroom {
let nameOfClass: String
let students: [Student] = []
}
let student1 = Student(firstName: "Keith", lastName: "Grimes", grade: "F")
let class1 = Classroom(nameOfClass: "Swift", students: student1)
我的最终目标是要填补一系列学生类型的学生,这本身使我感到困惑,但我只是想克服这第一个障碍。
答案 0 :(得分:0)
您需要删除= []
struct Classroom {
let nameOfClass: String
let students: [Student]
}
let student1 = Student(firstName: "Keith", lastName: "Grimes", grade: "F")
let class1 = Classroom(nameOfClass: "Swift", students: [student1])
讨论:
在结构体中添加属性的默认值时,它不会在自动init
方法中考虑它,并且将students
声明为数组并发送单个类型的对象Student
,然后将其包装在[]
中,如果您需要两者都包含,可以在
struct Classroom {
var nameOfClass: String
var students: [Student] = []
init(nameOfClass:String,students:[Student] = []) {
self.nameOfClass = nameOfClass
self.students = students
}
}
答案 1 :(得分:0)
学生是一组学生,也就是[学生],因此您需要通过[student1]或将让学生更改为学生