0

My current instructor insists that the proper way to initialize an object during runtime is as below:

class Person {
    var name: String; var age: Int
    init(name: String, age: Int){self.name = name; self.age = age}}

func CreatePerson (person: String, personName: String, personAge: Int){
    var \(person) = Person (name: personName, age: personAge)

CreatePerson(person:"Confused",personName:"Coder",personAge: 35)

Needless to say it is not quite so simple. \(person) in the func Create Person appears to solely be a String thing.

Sorry to bother you guys with what appears to be a simple process, but "That's how it's supposed to work" really isn't furthering my swift capabilities.

1
  • 1
    Does this code even compile? Commented Jun 23, 2016 at 2:58

1 Answer 1

2

Your instructor was wrong. First of all, what you showed was not valid Swift code. It will not compile. Second, he/she should teach you how to write readable code. In a professional environment, the person who wrote the code won't be the person who modifies it years later.

This is the most common way to initialize an object:

class Person {
    var name: String
    var age: Int

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

let person = Person(name: "John Smith", age: 42)

Obviously there are many others, depending on the situation and personal style.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.