MBH
MBH

Reputation: 16639

error when declaring a new object in a UIViewController in swift

I have created file called MyHelper.swift and I created class inside it:

public class MyHelper{
    //..... variables here
    public init(list listOfViews: [UIView]){
        self.listOfViews = listOfViews
        self.time = 1.0;
    }

}

then i declared an object in UIViewController like this

class ViewController: UIViewController {

    var myHelper: MyHelper;

    override func viewDidAppear(animated: Bool) {

        myHelper = MyHelper(listOfViewsToAnimatin: listOfViews)
    }

    // ..... rest of the code
}

but i got error that says:

**

Class "ViewController" has no initializers.

**

I tried the default fixes suggested in xcode:

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

It caused another error.

then i tried this code from internet:

required init(coder aDecoder: NSCoder!)
{
    super.init(coder: aDecoder)
}

It says :

Property self.myHelper not initialized at super.init call

How on earth i can use object of MyHelper class inside UIViewController !?

Upvotes: 0

Views: 1360

Answers (3)

Yichi Zhang
Yichi Zhang

Reputation: 21

You can make myHelper optional:

var myHelper:MyHelper?

When you use it, unwrap it first with:

if let myHelper = myHelper {
    myHelper.yourFunction()
} else {
    // self.myHelper == nil
}

Alternatively you can unwrap with !:

myHelper!.yourFunction()

But it will crash if myHelper is nil.

Upvotes: 1

Gavin Bunney
Gavin Bunney

Reputation: 1240

This is Swift's compile time checking at work.

You'll need to either setup the MyHelper in the init method, or mark it as optional (note the question mark at the end of the var declaration):

class ViewController: UIViewController {

    var myHelper: MyHelper?

    required init(coder aDecoder: NSCoder!)
    {
        super.init(coder: aDecoder)
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        myHelper = MyHelper(listOfViewsToAnimatin: listOfViews)
    }

    // ..... rest of the code
}

Upvotes: 2

MirekE
MirekE

Reputation: 11555

You are initializing the MyHelper in viewDidAppear. It needs to be initialized in init (before super.init()) or you need to declare it as optional and set to nil.

var myHelper: MyHelper? = nil

Upvotes: 1

Related Questions