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)

}

Replies

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!
  • Thank you for answering the question!

    for the CustomStringConvertible

    This is what I was supposed to do with code, to follow the following steps:

    Define a class called AboutMe Add 3 variables age, firstName, familyName Define an initializer for your variables within your class Create a new object called 'Me' and initialize the variables Create a custom description method to allow the following method call to work effectively print(Me) Define another object called Friend using the initializer Define another object called MeAgain using your details again

    I'm not sure if I have done the code correctly and if there is something I missed or done wrong.

Add a Comment

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