Expected declaration

Hello, I've been attempting to generate this code, but the last line returns an Expected declaration Error.

class AboutMe {

let firstName: String
let lastName: String
let age: Int


init(firstName: String, lastName: String, age: Int){
    self.firstName = firstName
    self.lastName = lastName
    self.age = age
}

var me: String {
    return "First Name: \(firstName), / Last Name: \(lastName), / Age: \(age)"
}

let myInfo = AboutMe(firstName: "NAME", lastName: "NAME", age: 10)
print(myInfo)

}

You have added your last two lines as part of the class definition, which is an error.
Try putting them in a method, like this:

func test() {
    let myInfo = AboutMe(firstName: "NAME", lastName: "NAME", age: 10)
    print(myInfo)
}

Note:

  • That will compile okay...
  • But it will probably not print what you are expecting, as you have not conformed "AboutMe" to CustomStringConvertible, but that's a different question!

What robnotyou said, plus:

You declare the class.

Then don't call its constructor inside:

class AboutMe {
    let firstName: String
    let lastName: String
    let age: Int

  init(firstName: String, lastName: String, age: Int){
    self.firstName = firstName
    self.lastName = lastName
    self.age = age
  }

  var me: String {
      return "First Name: \(firstName), / Last Name: \(lastName), / Age: \(age)"
   }

}

If you are in playground, call after the end of class:

let myInfo = AboutMe(firstName: "NAME", lastName: "NAME", age: 10)
print(myInfo)

If you are in an app, then you have another class (such as a ViewController), where you will call, for instance in viewDidLoad:

    override func viewDidLoad() {
        
        super.viewDidLoad()
        let myInfo = AboutMe(firstName: "NAME", lastName: "NAME", age: 10)
        print(myInfo)
    }

CustomStringConvertible

First conform AboutMe to CustomStringConvertible:

class AboutMe: CustomStringConvertible {

Then implement the description:

var description: String {
    "\(firstName) \(lastName), age: \(age)"
}
Expected declaration
 
 
Q