edward s
edward s

Reputation: 13

Class Array Error - "Expressions are not allowed at the top level"

I'm pretty new to coding Swift, so please excuse me if this error can be simply fixed!

I've created a data model using swift in Xcode, and created a variable array in order to have the student detail and properties. This code works on swift playgrounds without errors, but when I use it inside a project, I get a "Expressions are not allowed at the top level" Error in the variable line. The class and object is the following -

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)

I've tried to put the variable arr inside class view controller, but that just triggers up more errors. I've tried looking at similar questions, but none of them directly help my problem.

Upvotes: 0

Views: 360

Answers (2)

Sweeper
Sweeper

Reputation: 271775

Statements like arr.append(user1Detail) can only go in closures (which includes methods, functions, initialisers, etc). Declarations can go in a class or the global level.

Your file can look like this:

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)
    }
}

Upvotes: 1

Joakim Danielson
Joakim Danielson

Reputation: 51973

You have to have all your code that declares and uses properties inside a class or struct

Do something like this with the second part of your code

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)
    }

Not a very usable class but quick example on what you need to do

Upvotes: 0

Related Questions