Skip to content

Instantly share code, notes, and snippets.

@hboon
Created April 11, 2020 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hboon/57c2d0bab5d637c6d939ad954556ec72 to your computer and use it in GitHub Desktop.
Save hboon/57c2d0bab5d637c6d939ad954556ec72 to your computer and use it in GitHub Desktop.
self when initialising property with function, inheriting from NSObject
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