Razvan Soneriu Razvan Soneriu - 3 months ago 12x
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() {


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.