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
}
}