Created
April 11, 2020 05:41
-
-
Save hboon/57c2d0bab5d637c6d939ad954556ec72 to your computer and use it in GitHub Desktop.
self when initialising property with function, inheriting from NSObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Found a bug in my code because of something very subtle: | |
``` | |
class C: NSObject { | |
var foo: String = { | |
NSLog("non-lazy self: \(self)") | |
return "" | |
}() | |
lazy var bar: String = { | |
NSLog("lazy self: \(self)") | |
return "" | |
}() | |
} | |
let c = C() | |
let _ = c.bar | |
``` | |
prints: | |
``` | |
2020-04-11 13:38:50.989 Untitled 2[98985:8257392] non-lazy self: (Function) | |
2020-04-11 13:38:50.989 Untitled 2[98985:8257392] lazy self: <main.C: 0x7fe0b6d02ae0> | |
``` | |
Bonus, code doesn't compile if C doesn't inherit from NSObject (so reproducible by replacing NSObject with say UIViewController). I encountered this because I had `foo` which calls `addTarget(_:action:)` with `self as the target` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment