lazy variables in Swift - should be read-only


Quincey Morris
 

On Jul 11, 2018, at 00:04 , Gerriet M. Denkmann <g@...> wrote:

What I really want:
• session should be set exactly once at the first time it is used.
• the compiler should generate an error if somebody tries to set it (like with “let”).

You can do something like this:

    private(set) lazy var session: URLSession = {
        let sessionConfig = URLSessionConfiguration.ephemeral
        return URLSession( configuration: sessionConfig )
    }()

It’s settable from within its class or struct, but not from outside, which is as close as you can get to ‘lazy let’ AFAIK.


Gerriet M. Denkmann
 

This works:

lazy var session = makeSession()
func makeSession() -> URLSession
{
let sessionConfig = URLSessionConfiguration.ephemeral
return URLSession( configuration: sessionConfig )
}

First: is it possible to avoid this one-time function “makeSession” ?
(Assume that makeSession could not be reduced to one line, e.g. add a print() into it)

More important: anybody can set any value to “session”. This is not what I want.

What I really want:
• session should be set exactly once at the first time it is used.
• the compiler should generate an error if somebody tries to set it (like with “let”).

Can this be accomplished? If so, how?

Gerriet.