1

I came across some old Swift code (badly written from when I was first playing with the language back in June) and I was curious why the function test fails, but test2 works?

fatal error: unexpectedly found nil while unwrapping an Optional value

Its a silly example as self.node would need adding to the scene. I was just curios as to why they behave differently, my guess is its maybe the way each is implemented or the way the complier handles each knowing there correct use.

class GameScene: SKScene {
    weak var node: SKNode!
    weak var color: SKColor!

    func test() {
        self.node = SKNode()
        print(self.node) // Why nil here?
    }

    func test2() {
        self.color = SKColor()
        print(self.color) // Works fine ...
    }
}

I understand the objects are created in the scope of the function and assigned to a variable declared as weak, its more about why the difference?

fuzzygoat
  • 26,573
  • 48
  • 165
  • 294

1 Answers1

2

Put simply, the value of a weak variable will only be determined at run-time. You can read more about this at: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48

Rajinikanth
  • 369
  • 1
  • 9
  • Much appreciated, I will check that out. Thank you Sir – fuzzygoat Sep 23 '15 at 06:24
  • Can you paste the paragraph/explanation you refer to, the only thing I can find in the linked doc is "Weak references must be declared as variables, to indicate that their value can change at runtime. A weak reference cannot be declared as a constant." – fuzzygoat Sep 23 '15 at 08:51