0

How can I call a class function from an initializer? I'm looking for something that would work like:

class A {
  var name: String

  class func getName() -> String {
    return "first class"
  }

  init() {
    self.name = Type.getName()
  }
}

class B: A {
  var bar: String

  override class func getName() -> String {
    return "second class"
  }

  init() {
    self.bar = "bar"
    super.init()
  }
}

A().name // "first class"
B().name // "second class"
B().bar // "bar"

(I'm looking at class functions since they can be overwritten and called before the instance is initialized)

=== Edit ===

This question is well answered by: https://stackoverflow.com/a/24711715/2054629

amusingly xcode fails to compile something like:

class A {
  var id: String
  class func getId() -> String {
    return ":)"
  }

  init(from id: String?) {
    let finalId = id ?? type(of: self).getId()
    self.id = finalId
  }
}

with: 'self' captured by a closure before all members were initialized

while just using let finalId = type(of: self).getId() works fine.

Community
  • 1
  • 1
Guig
  • 9,891
  • 7
  • 64
  • 126
  • As [the answer here shows](http://stackoverflow.com/a/40159283/2976878), use `type(of: self)`, e.g `type(of: self).getName()` – Hamish Mar 16 '17 at 21:15
  • Thanks. Sorry I didn't see that before. I was also unsure I could use `self` before finishing the initialization, but that just works. – Guig Mar 16 '17 at 21:17
  • Generally, you cannot use `self` before all stored properties are initialized, but there are some exceptions to the rule, `type(of: self)` being one of them (it's perfectly safe to use before initialisation is complete because it doesn't depend on any instance state). – Hamish Mar 16 '17 at 21:19

0 Answers0