0

When I call the following, the compiler complains that I am missing argument for parameter #1 in call :

import Foundation

class Person {

    func uniqueID() -> String {
        return NSUUID().UUIDString
    }

    lazy var sessionID: String = uniqueID()

}


let p = Person()

p.sessionID
p.sessionID
p.sessionID

When I replace the line with:

lazy var sessionID: String = NSUUID().UUIDString

It works.

What is causing the problem calling the function in a lazy initialization?

Interestingly, calling a closure works, even if the syntax looks clunky and heavy, as I would have to guard it if self is a weak reference:

lazy var sessionID: String = {
    return self.uniqueID()
}()

1 Answer 1

1

The issue is you're missing the reference to self. You have it in the closure but not in the direct method call.

lazy var sessionID = self.uniqueID()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Should I always use self. when I call methods idiomatically? Omitting it on traditional calls seems to work, but 'lazy' behaves differently. Why is that?
Just guessing, but it looks like a lazy initialization is essentially always treated as a closure, so they follow the rule that self must be explicit.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.