Search code examples
swiftweak-references

swift 4 weak variable


In below code, why when car1 variable was assigned nil , car2 is not nil? Can someone explain it?.I am asking this question because of that I know when all strong references of a object was assigned nil , all other weak references are assigned nil automatically.is it wrong?

Thank you so much.

class ViewController: UIViewController {
    var car1 : Car? = Car()
    weak var  car2 : Car?

    override func viewDidLoad() {
        super.viewDidLoad()
        car2 = car1
        car1 = nil
        print("gfehtre")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Solution

  • Not sure what your question is: car2 is not nil only when car2 = car1 is executed on the next line car1 = nil car2 also becomes nil,

    Test it yourself by:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        if let _ = car2 {
            print("first")
        }
    
        car2 = car1
    
        if let _ = car2 {
            print("second")
        }
    
        car1 = nil
    
        if let _ = car2 {
            print("third")
        }
    }
    

    You will see in console that only second is printed in all other cases car2 is nil