Reputation: 26223
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?
Upvotes: 1
Views: 274
Reputation: 359
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
Upvotes: 2