Calling instance method during initialization in Swift

前端 未结 7 1532
别跟我提以往
别跟我提以往 2020-12-06 01:08

I am new to Swift and would like to initialize an object\'s member variable using an instance method like this:

class MyClass {
  var x: String
  var y: Stri         


        
7条回答
  •  萌比男神i
    2020-12-06 01:44

    see Two-Phase Initialization, and the example : https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html#ID52 at Unowned References and Implicitly Unwrapped Optional Properties

    class Country {
        let name: String
        var capitalCity: City!
        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
        }
    }
    

    To set up the interdependency between the two classes, the initializer for City takes a Country instance, and stores this instance in its country property.

    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, indicated by the exclamation mark at the end of its type annotation (City!). This means that the capitalCity property has a default value of nil, like any other optional, but can be accessed without the need to unwrap its value as described in Implicitly Unwrapped Optionals.

    Because capitalCity has a default nil value, a new Country instance is considered fully initialized as soon as the Country instance sets its name property within its initializer. This means that the Country initializer can start to reference and pass around the implicit self property as soon as the name property is set. The Country initializer can therefore pass self as one of the parameters for the City initializer when the Country initializer is setting its own capitalCity property.

    so add a exclamation mark of y's type -> var y: String!

提交回复
热议问题