Peterdk
Peterdk

Reputation: 16015

how to share a initialize function between two init functions in Swift?

I am used to writing a shared - (void) initialize function to handle both initWithFrame and initWithCoder functions in Objective-C.

However, in Swift I don't seem to be allowed to call a function to do that before calling super.init() and also not after that, since the properties need to be initialized before that.

I think writing a initWithFrame is not that important anymore but what if I have a custom class with multiple init methods that I want to simplify by using a shared initializer?

Before super.init():

required init?(coder aDecoder: NSCoder) {        
    self.initialize()//use of self in method call initialize before super.init()
    super.init(coder: aDecoder)    
}

After super.init():

required init?(coder aDecoder: NSCoder) {        
    super.init(coder: aDecoder)
    self.initialize()//property not initialized at super.init call
}

`

Upvotes: 0

Views: 771

Answers (1)

vadian
vadian

Reputation: 285064

That depends on the stored properties to be initialized.

For example you could assign a default value to the properties

class Foo {

   var name = ""
   var age = 0

   let formatter : DateFormatter = {
       let df = DateFormatter()
       df.dateFormat = "yyyy/MM/dd"
       return df
   }()
}

or use implicit unwrapped optionals

class Foo {

   var name = String!
   var age = Int!

   var formatter : DateFormatter! 

}

In both cases all properties are initialized and you can first call super and then the initialize method. However the first way is recommended for type safety reasons.

Anyway the rule is:

  • All non-optional properties must be initialized before calling super and self can be only used after calling super

Upvotes: 1

Related Questions