类数组错误-“不允许在顶层表达”

时间:2019-01-06 08:08:46

标签: arrays swift variables

我对Swift编码还很陌生,所以请简单解决此错误!

我已经在Xcode中使用swift创建了一个数据模型,并创建了一个变量数组以具有学生的详细信息和属性。这段代码可以在快速的操场上正常运行,但是没有错误,但是当我在项目中使用它时,在变量行中出现“在顶层不允许表达”错误。类和对象如下-

class StudentDetail {

//Create Student Properties
var n: String?
var s: String?
var g: String?

//Initialise Properties
init(name: String, subject: String, grade: String) {
    self.n = name
    self.s = subject
    self.g = grade
}
}


let user1Detail = StudentDetail(name: "Koester", subject: "Science", grade: "9A")
let user2Detail = StudentDetail(name: "Tilly", subject: "Math", grade: "9A")

let people = [user1Detail, user2Detail]

//Variable Array
var arr = [StudentDetail]()
arr.append(user1Detail)
arr.append(user2Detail)

我试图将变量arr放在类视图控制器中,但这只会引发更多错误。我曾尝试查看类似的问题,但没有一个问题可以直接帮助解决我的问题。

2 个答案:

答案 0 :(得分:0)

您必须拥有所有在类或结构中声明和使用属性的代码

在代码的第二部分做类似的事情

class Test {

    let user1Detail = StudentDetail(name: "Koester", subject: "Science", grade: "9A")
    let user2Detail = StudentDetail(name: "Tilly", subject: "Math", grade: "9A")

    let people = [user1Detail, user2Detail]
    func doStuff() {
       //Variable Array
        var arr = [StudentDetail]()
        arr.append(user1Detail)
        arr.append(user2Detail)
    }

这不是一个非常有用的类,而是关于您需要做什么的简单示例

答案 1 :(得分:0)

诸如arr.append(user1Detail)之类的语句只能放在闭包中(包括方法,函数,初始化程序等)。声明可以放在一个类或全局级别。

您的文件如下所示:

class StudentDetail {

    //Create Student Properties
    var n: String?
    var s: String?
    var g: String?

    //Initialise Properties
    init(name: String, subject: String, grade: String) {
        self.n = name
        self.s = subject
        self.g = grade
    }

}

class ViewController: UIViewController {
    let user1Detail = StudentDetail(name: "Koester", subject: "Science", grade: "9A")
    let user2Detail = StudentDetail(name: "Tilly", subject: "Math", grade: "9A")

    let people = [user1Detail, user2Detail]
    var arr = [StudentDetail]()

    override func viewDidLoad() {
       arr.append(user1Detail) // now this is in a method
       arr.append(user2Detail)
    }
}