Poweranimal
Poweranimal

Reputation: 1699

Swift: Not initialised Lazy Variable that returns Closure

I have a lazy variable that is not initialised:

lazy var time: () -> String = {
    return String(describing: Date())
}

Whenever I call time() I get a new Date. So it seems like it behaves exactly like:

var time: () -> String {
    return {
        return String(describing: Date())
    }
}

In this context, is it bad practice just to use the lazy closure, because then I don't have to write two return-statements in a row or do I miss something?

Upvotes: 1

Views: 422

Answers (1)

Sweeper
Sweeper

Reputation: 271050

You don't need two return statements in a row nor do you need a lazy closure. Why not just do:

let time: () -> String = {
    return String(describing: Date())
}

Or just replace this whole thing with a method:

func time() -> String {
    return String(describing: Date())
}

One reason why you might want to use a closure here is that you want other parts of your code to change the value of the closure. If that's the case, just do it like the first snippet, otherwise I don't think anything is preventing you from writing a method. You can pass a method around just like a closure, because methods are a kind of closure!

Lazy variables are really needed when initializing them takes much resources. Creating closures tend to be cheap.

Upvotes: 2

Related Questions