Skip to content

Instantly share code, notes, and snippets.

@hboon
Last active April 11, 2020 05:47
Show Gist options
  • Save hboon/93f58cc785a73d871eafeb5503457f1d to your computer and use it in GitHub Desktop.
Save hboon/93f58cc785a73d871eafeb5503457f1d 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 and was wondering why the action never fires.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment