2

Consider this example

class Foo {
    private let bar = "bar"

    lazy var baz : String = {
        return "baz \(bar)"
    }()
}

Unfortunately this won't compile and give the following error

'Foo.Type' does not have a member named 'bar'

I really do not want to declare bar outside the class (globally). Is there no other way to keep this inside the class and why isn't bar accessible in the first place?

0

2 Answers 2

4

TL;DR: preface with self

Swift can be quite misleading with error messages, but in this case, the answer can be deduced from the message. It is looking for bar on type Foo.Type, whereas you are trying to reference an instance variable. Here is code that works:

class Foo {
    private let bar = "bar"

    lazy var baz : String = {
        return "baz \(self.bar)"
    }()
}
Sign up to request clarification or add additional context in comments.

1 Comment

aaah... thanks. The devil is in the details - or misleading error messages.
1

In lazy props you need to say self

lazy var baz : String = {
    let bar = self.bar
    return "baz \(bar)"
}()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.