swiftclassswift-playgroundswift-class

class in playground vs in program file


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)

Solution

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