代码-情形1:
// 两个属性的值都允许为nil,这种场景最适合用弱引用来解决 class Person { let name: String init(name: String) { self.name = name } // 弱引用 var apartment: Apartment? deinit { print("\(name) is being deinitialized") } } class Apartment { let number: Int init(number: Int) { self.number = number } // 弱引用 weak var tenant: Person? deinit { print("Apartment #\(number) is being deinitialized") } } var John: Person? = Person(name: "John") var Number73: Apartment? = Apartment(number: 73) John!.apartment = Number73 Number73!.tenant = John John = nil Number73 = nil
代码-情形2:
// 一个属性的值允许为nil,而另一个属性的值不允许为nil,这种场景最适合通过无主引用来解决 class Customer { let name: String var card: CreditCard? init(name: String) { self.name = name } deinit { print("\(name) is being deinitialized") } } class CreditCard { let number: UInt64 // 无主引用,不会对实例产生强引用 unowned 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
代码-情形3:
// 两个属性都必须有值,并且初始化完成后永远不会为nil // 这种场景最适合通过一个类使用无主属性,而另外一个类使用隐式解析可选属性来解决 class Country { 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") } } class City { 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
时间: 2024-11-05 16:39:24