Why would you create a \"Implicitly Unwrapped Optional\" vs creating just a regular variable or constant? If you know that it can be successfully unwrapped then why create a
Apple gives a great example in The Swift Programming Language -> Automatic Reference Counting -> Resolving Strong Reference Cycles Between Class Instances -> Unowned References and Implicitly Unwrapped Optional Properties
class Country {
let name: String
var capitalCity: City! // Apple finally correct this line until 2.0 Prerelease (let -> var)
init(name: String, capitalName: String) {
self.name = name
self.capitalCity = City(name: capitalName, country: self)
}
}
class City {
let name: String
unowned let country: Country
init(name: String, country: Country) {
self.name = name
self.country = country
}
}
The initializer for
City
is called from within the initializer forCountry
. However, the initializer forCountry
cannot passself
to theCity
initializer until a newCountry
instance is fully initialized, as described in Two-Phase Initialization.To cope with this requirement, you declare the
capitalCity
property ofCountry
as an implicitly unwrapped optional property.