Code-Scenario 1:
//The values of the two properties are allowed to nil, which is best suited for use with weak references to solveclassPerson {Let name:string init (name:string) {self.name=name}//Weak referencesvar apartment:apartment?deinit {print ("\ (name) is being deinitialized") }}classApartment {let Number:int init (number:int) {Self.number=Number }//Weak referencesWeak var Tenant:person?deinit {print ("Apartment #\ (number) is being deinitialized")}}var John:person? = Person (name:"John") var number73:apartment? = Apartment (number: the) John!. Apartment =number73number73!. Tenant =Johnjohn=nilNumber73= Nil
Code-Scenario 2:
//The value of one property is allowed to be nil, while the value of another property is not allowed to nil, and this scenario is best addressed by a no-master referenceclassCustomer {let name:string var card:creditcard?Init (name:string) {self.name=name} deinit {print ("\ (name) is being deinitialized") }}classCreditCard {Let Number:uint64//No primary reference, no strong reference to the instanceunowned let Customer:customer init (Number:uint64, Customer:customer) {Self.number=Number Self.customer=Customer} deinit {print ("Card #\ (number) is being deinitialized")}}var John:customer? = Customer (Name:"John Appleseed") John!. Card = CreditCard (number:1234_5678_9012_3456, customer:john!) John= Nil
Code-Scenario 3:
//Two attributes must have a value, and will never be nil after initialization is complete//This scenario is best for using a non-primary property through one class, while another class uses the implicit parsing of optional properties to resolveclassCountry {Let name:string var capitalcity:city!Init (name:string, capitalname:string) {self.name=name Self.capitalcity=City (Name:capitalname, country:self)} deinit {print ("country named \ (name) is being deinitialized") }}classCity {Let name:string unowned let Country:country init (name:string, country:country) {Self.name =name Self.country=Country} deinit {print ("City named \ (name) is being deinitialized")}}var Country:country? = Country (Name:"Canada", Capitalname:"Ottawa") Country= Nil
Solutions for Swift class instances and circular references