Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a subclass of UIViewController with Swift?

Tags:

ios

swift

ios8

I'm trying to understand how initialization works in Swift with a subclass of a UIViewController. I thought the basic format was this, but it is throwing errors...

init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)   {
    //other code
    super.init(nibName: String?, bundle: NSBundle?)
}
like image 451
user3587825 Avatar asked Jun 03 '14 08:06

user3587825


People also ask

How do I initialize a view controller in Swift?

Open ImageViewController. swift and add an initializer with name init(coder:image:) . The initializer accepts an NSCoder instance as its first argument and an Image object as its second argument.

What is Failable initializer in Swift?

A failable initializer creates an optional value of the type it initializes. You write return nil within a failable initializer to indicate a point at which initialization failure can be triggered. ie; if a condition fails, you can return nil . IMPORTANT: In swift, the initializers won't return anything.

What is convenience init Swift?

Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer's parameters set to default values.

What is a UIViewController?

The UIViewController class defines the shared behavior that's common to all view controllers. You rarely create instances of the UIViewController class directly. Instead, you subclass UIViewController and add the methods and properties needed to manage the view controller's view hierarchy.


2 Answers

You're passing the types, not the variables. You have to pass the variables instead.

init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)  {
    // Initialize variables.

    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
like image 182
Leandros Avatar answered Oct 19 '22 00:10

Leandros


Variables should now be initialized before the call to super.init

init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)  {

    // Initialize variables.

    super.init() // as required
}
like image 43
JulioBarros Avatar answered Oct 19 '22 00:10

JulioBarros