Razvan Soneriu Razvan Soneriu - 1 year ago 92
Swift Question

Swift lazy instantiating using self

I have something that really puzzles me, specifically the following code triggers a compiler error "unresolved identifier self", and I am not sure why this is happening, as lazy means that at the time the property will be used, the class is already instantiated. Am I missing something?

Many thanks in advance.

Here is the code

class FirstClass {
unowned var second: SecondClass

init(second:SecondClass) {
self.second = second
print("First reporting for duty")

func aMethod() {
print("First's method reporting for duty")

class SecondClass {

lazy var first = FirstClass(second: self)

func aMethod() {

Answer Source

For some reason (which I cannot explain, perhaps someone else can), a lazy property needs an explicit type annotation if its initial value refers to self. With

lazy var first: FirstClass = FirstClass(second: self)

your code compiles and runs as expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download