Matrosov Alexander Matrosov Alexander - 1 year ago 60
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() = name

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

let person = getConiguratedPerson("Alex")

but what if I need
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 Source

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) { = name

  init(object: PersonEntity) {

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:].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download