Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
class Person {}
class Flat {
weak var tenant: Person?
}
var anna: Person? = Person()
let flat = Flat()
flat.tenant = anna
print(flat.tenant == nil)
anna = nil
print(flat.tenant == nil)false true
- Expecting
false false: thinking aweakreference keeps the object. It adds nothing to the count, soanna = nilfrees the person andtenantbecomesnil. - Expecting a crash: mixing up
weakwithunowned. Aweakreference to a freed object isnil, and the program goes on.
- What does the program print if
tenantis declared withoutweak? - What happens if you write
flat.tenant = Person()instead of usinganna?