Matrosov Alexander Matrosov Alexander - 2 months ago 9
Swift Question

Swift inheritance issue. How to get appropriate class object

I have two classes (to simplify I drop other filed the object is more complicated then the Person):

class Person
{
var name: String = "Default name"

init(object: PersonEntity)
{
name = object.daysMask
}
}

class Employer: Person
{

}


I have function that configure for me a person

func getConiguratedPerson(name: String) -> Person
{
let person = Person()
person.name = name
}


In case if I want to get
Person
I simple do this:

let person = getConiguratedPerson("Alex")


but what if I need
Employer
instead and I want to use this function as well

let employer = getConiguratedPerson("Alex") // returns Person as expected but need to have employer instead.


In Objective-C we can simple do this:

Employer *employer = Employer([self getConiguratedPerson:"Alex"]) if I remember.

Answer

The mistake is the getConfiguredPerson function. You want an initializer. Initializers return your own class, which is exactly what you want.

class Person {
  var name: String = "Default name"

  init(name: String) {
      self.name = name
  }

  init(object: PersonEntity) {
      self.init(object.daysMask)
  }
}

class Employer: Person {}

Now to create a person, you just use Person(name: "Alex") and to get an employer you use Employer(name: "Alex").

Note that this is true in ObjC as well. You shouldn't have getConfiguredPerson there either. You'd should have [Person initWithName:].