简体   繁体   中英

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 !?

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
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM