2016-07-15 3 views
1

다음 코드는 PersonApartment을 정의합니다. Person 인스턴스는 Apartment, Apartment 세입자 (Person 인스턴스)약한 참조를 통해 속성을 nil로 설정할 수 없습니다.

class Person { 
    let name: String 
    init(name: String) { self.name = name } 
    var apartment: Apartment? 
    deinit { print("\(name) is being deinitialized") } 
} 

class Apartment { 
    let unit: String 
    init(unit: String) { self.unit = unit } 
    weak var tenant: Person? 
    deinit { print("Apartment \(unit) is being deinitialized") } 
} 

var john: Person? 
var unit4A: Apartment? 

john = Person(name: "John Appleseed") 
unit4A = Apartment(unit: "4A") 

john!.apartment = unit4A 
unit4A!.tenant = john 

다음 위의 코드는 또한 그래픽으로 표시 할 수있을 수있다 소유. enter image description here

이제 다음 코드는 예를 john

john = nil 

if let per = unit4A!.tenant { 
    print("\(per.name) is a ghost person") \\This line is prented out, isn't it already a set with `nil`? 
} else { 
    print("all nil dude") 
} 

enter image description here

문제 해제하기 위해 실행됩니다 엑스 코드는 (마지막 그림 참조) niltenant 속성을 설정하지 않습니다

에게

질문 : 어떻게 해결할 수 있습니까? 내가 IBM Swift SandBox 코드를 시도하고 잘 작동, Xcode 버그가 있습니까?

감사합니다.

enter image description here

답변

1

놀이터는 마귀의 일이다. 놀이터가 아닌 실제 앱 프로젝트에서 테스트 해보면 예상대로 작동한다는 것을 알 수 있습니다.

+0

매트 덕분에 그것을 시험해 보겠습니다. – SLN

+1

예제 코드는 다음과 같습니다. https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk1ch05p254memoryManagement/bk1ch05p254memoryManagement/ViewController.swift 수행중인 작업과 동일한 원리를 보여줍니다. – matt