0

I have a question regarding Swift.

I know when we create a designated initializer in Objective-C, sometimes we may need to do this(in order to load the corresponding .xib file):

if ((self = [super initWithNibName:@"PPFrameViewController" bundle:nil]))
{
}

What would be the equivalent in Swift. Just:

super.init(nibName: "PPFrameViewController", bundle: nil)

?

or something more?

Thanks in advance

ppalancica
  • 4,236
  • 4
  • 27
  • 42
  • https://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/occ/instm/UIViewController/initWithNibName:bundle: – Tirth Nov 07 '14 at 04:44
  • This questions in NOT ABOUT optionals; it is about the calling sequence of designated initializers. Thus, @Tirth, your DUPLICATE reference is incorrect. – GoZoner Nov 07 '14 at 16:00

1 Answers1

0

For UIViewController the designated initializer is as you state:

init(nibName  nibName: String?,
     bundle nibBundle: NSBundle?)

therefore in your designated initializer you invoke it, after you have initialized the subclass properties:

  // subclass properties initialized
  super.init(nibName: <name>, bundle: <bundle>)
  // any other initialization
GoZoner
  • 67,920
  • 20
  • 95
  • 145
  • thank you! but why after and not before(as the first line)? – ppalancica Nov 07 '14 at 14:12
  • The Apple documentation takes about 'safety' in initialization. All subclass properties need to be initialized before the parent/super is initialized. Presumably this is so that any calls by the super init could be overridden buy subclass functions that need to have properties initialized. – GoZoner Nov 07 '14 at 15:34
  • I am kind of confused, because in Objective-C we always make the statement self = [super init]; as the first line, also in Java we must write super(); as the first line in constructors (or the compiler will do that for us). As far as I know, according to OOP paradigms, we must first initialize the properties from the super class and then the properties of the current class itself. Is it in Swift this should be done different? – ppalancica Nov 07 '14 at 17:19
  • This is Swift 'Two Phase Initialization'. In Swift in the designated initilizer(s) of a subclass, the subclass properties need to be initialized before the superclass designed initializer is called. This happens in Objective-C whereby all the properties are assigned `0` or `nil` before the `super init` is called - it happens behind your back. In Swift, you get to be explicit about it. – GoZoner Nov 07 '14 at 20:54