Class 'ViewController' Has No Initializers In Swift
Answer :
The error could be improved, but the problem with your first version is you have a member variable, delegate
, that does not have a default value. All variables in Swift must always have a value. That means that you have to set it up in an initializer which you do not have or you could provide it a default value in-line.
When you make it optional, you allow it to be nil
by default, removing the need to explicitly give it a value or initialize it.
The Swift Programming Language states:
Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.
You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.
Therefore, you can write:
class myClass { var delegate: AppDelegate //non-optional variable init() { delegate = UIApplication.sharedApplication().delegate as AppDelegate } }
Or:
class myClass { var delegate = UIApplication.sharedApplication().delegate as AppDelegate //non-optional variable init() { println("Hello") } }
Or:
class myClass { var delegate : AppDelegate! //implicitly unwrapped optional variable set to nil when class is initialized init() { println("Hello") } func myMethod() { delegate = UIApplication.sharedApplication().delegate as AppDelegate } }
But you can't write the following:
class myClass { var delegate : AppDelegate //non-optional variable init() { println("Hello") } func myMethod() { //too late to assign delegate as an non-optional variable delegate = UIApplication.sharedApplication().delegate as AppDelegate } }
Sometimes this error also appears when you have a var or a let that hasn't been intialized.
For example
class ViewController: UIViewController { var x: Double // or var y: String // or let z: Int }
Depending on what your variable is supposed to do you might either set that var type as an optional or initialize it with a value like the following
class ViewController: UIViewCOntroller { // Set an initial value for the variable var x: Double = 0 // or an optional String var y: String? // or let z: Int = 2 }
Comments
Post a Comment