ntoonio
ntoonio

Reputation: 3143

Why not using static variable directly in Swift?

I found this in the Mozilla Firefox for iOS repository.

static let WebServerSharedInstance = WebServer()

class var sharedInstance: WebServer {
    return WebServerSharedInstance
}

Why would you create a new variable that just returns the same variable when you could do the same in one line like this?

static let sharedInstance = WebServer()

Upvotes: 1

Views: 358

Answers (3)

Sulthan
Sulthan

Reputation: 130162

I have looked into the code and I think I have misunderstood the context:

class WebServer {
    static let WebServerSharedInstance = WebServer()

    class var sharedInstance: WebServer {
        return WebServerSharedInstance
    }
}

While you can always use WebServer.WebServerSharedInstance to access the singleton, a subclass of WebServer can override sharedInstance.

class MyServer : WebServer {
    override class var sharedInstance: MyServer {
        return MyServer()
    }
}

However, I have found no example in the code doing that so the original answer below is probably correct.

Original answer:

You are right. There is absolutely no reason to do that.

This has been probably translated directly from Objective-C, which uses similar syntax for singletons.

Also, with Swift 1.0 we weren't very sure how to create singletons and whether static let on a class is Thread safe.

Upvotes: 2

Developer Omari
Developer Omari

Reputation: 434

A suggestion is that WebServerSharedInstance is a global variable declared at the top level of the file which lives as long as the file lives which is as long as the program runs --> You can use that variable in all other files

Upvotes: 0

MadNik
MadNik

Reputation: 7793

I'm not sure the context. But let me explain one of the key differences between

// 1
class var sharedInstance: WebServer {
    return WebServerSharedInstance
}

vs

// 2
static let sharedInstance = WebServer()

1 is computed variable which gets evaluated each time you access, while 2 get initialized lazily and evaluated only once.

If later in your code someone reassigns the WebServerSharedInstance

The 1 will return the new value while 2 will keep returning the initial value if it got initialized before.

Upvotes: 0

Related Questions