Swift编程语言指南包含以下示例:
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { println("\(name) is being deinitialized") }
}
class Apartment {
let number: Int
init(number: Int) { self.number = number }
var tenant: Person?
deinit { println("Apartment #\(number) is being deinitialized") }
}
var john: Person?
var number73: Apartment?
john = Person(name: "John Appleseed")
number73 = Apartment(number: 73)
//From Apple's “The Swift Programming Language” guide (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html)
然后,在将公寓分配给该人时,他们使用感叹号“解开实例”:
john!.apartment = number73
“解开实例”是什么意思?为什么有必要?它与仅执行以下操作有何不同:
john.apartment = number73
我是Swift语言的新手。只是想降低基础知识。
更新:
我遗漏的一大难题(未在答案中直接说明-至少在撰写本文时没有)是在执行以下操作时:
var john: Person?
正如我最初所认为的,这并不意味着“ john
是类型Person
,可能为零”。我只是误解了Person
,Person?
它们是完全独立的类型。一旦我掌握了,所有其他的?
,!
疯狂的,和下面的伟大的答案,做了很多更有意义。