0

I have a question about something simple that works in Playground but not in a Project: (Playground code below)

In the project where the class is in a separate swift file the code correction won't show me the the person.lastName and if I fully type it give me an error.... hmm, very strange - might be a beginner error or?

How would I have to state in in the program file and the separate swift file to work?

Thanks, Roman

import UIKit

class human {
    var firstName = ""
    var lastName = ""
}

let person = human()

person.lastName = "Smith"
person.firstName = "Peter"

print (person.firstName)
print (person.lastName)
RoGe
  • 19
  • 2
  • 2
    It's because in playgrounds there is a special rule that top-level executable statements are allowed; but elsewhere executable statements must be inside a function body. What is the "separate swift file" and what are you doing to make it execute? – matt Jan 19 '20 at 21:55
  • Thanks, I am setting up an app that shows a list of people (person) - each one mad up from a couple of data types (first name, last name, etc.) - for the human class i want to define that in a separate swift class file in the project, the rest i want to run and show in the UI in the ViewController.swift file but it didn't work... – RoGe Jan 19 '20 at 22:05

1 Answers1

0

This is why I hate playgrounds. They are not really Swift. In real Swift, all executable code must be inside a function (e.g. a method of some class or struct or enum); you can't have lines like person.lastName = "Smith" just hanging in space like that.

So in a real iOS project you'd need to write something more like this:

class Human {
    var firstName = ""
    var lastName = ""
}

func test() {

    let person = Human()

    person.lastName = "Smith"
    person.firstName = "Peter"

    print (person.firstName)
    print (person.lastName)

}

And even then nothing would happen until you actually call test(), and you can't do that except in a function. This is why people usually test code in the viewDidLoad of a view controller.

class Human {
    var firstName = ""
    var lastName = ""
}
class ViewController : UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let person = Human()

        person.lastName = "Smith"
        person.firstName = "Peter"

        print (person.firstName)
        print (person.lastName)

    }
}
matt
  • 515,959
  • 87
  • 875
  • 1,141