Why create “Implicitly Unwrapped Optionals”, since that implies you know there's a value?

前端 未结 10 1785
深忆病人
深忆病人 2020-11-22 07:30

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

10条回答
  •  不知归路
    2020-11-22 08:04

    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 for Country. However, the initializer for Country cannot pass self to the City initializer until a new Country instance is fully initialized, as described in Two-Phase Initialization.

    To cope with this requirement, you declare the capitalCity property of Country as an implicitly unwrapped optional property.

提交回复
热议问题