PGDev
PGDev

Reputation: 24341

Singleton and Class Properties in Swift

I am trying to create a singleton class. For this I have tried to use two different approaches i.e.

1.First approach - Employee class contains two instance properties, a class property that contains the shared instance of the class and a private initializer, i.e.

class Employee
{
    var firstName : String
    var lastName : String

    static let sharedInstance = Employee(firstName: "Payal", lastName: "Gupta")

    private init(firstName : String, lastName : String)
    {
        self.firstName = firstName
        self.lastName = lastName
    }
}

2.Second approach - Employee2 class contains two class properties, i.e.

class Employee2
{
    static var firstName : String = "SomeFirsrName"
    static var lastName : String = "SomeLastName"
}

Are these two approaches of making the singleton equivalent? If yes, which one should I use and what are the differences between each of them in respect of singleton?

Upvotes: 1

Views: 1840

Answers (3)

Alessandro Ornano
Alessandro Ornano

Reputation: 35392

To make a simple singletone class in Swift you could write:

class SomeManager {
    static let sharedInstance = SomeManager()
}

Usage:

SomeManager.sharedInstance

What does it mean?

Since Swift 1.2 it's possible do declare static class properties. So you can implement the singleton like this. There can only be one instance for the lifetime of the application it exists in. Singletons exist to give us singular global state.

The first approach create a singletone having a class with this initialization: Employee(firstName: "Payal", lastName: "Gupta")

The second approach don't create a singletone, is a simple class with two static declared properties.

Upvotes: 3

Amit Kalghatgi
Amit Kalghatgi

Reputation: 367

Try this...

class Employee : NSObject
    {
        var firstName : String
        var lastName : String
        class var sharedInstance: Employee {
            struct Static {
                static let instance: Employee = Employee(firstName: "Payal", lastName: "Gupta")
            }
            return Static.instance
        }

        private init(firstName : String, lastName : String)
        {
           self.firstName = firstName
           self.lastName = lastName
        }
    }

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

These two approaches are not equivalent:

  • The first approach creates an instance of Employee object
  • The second approach defines two class fields; it does not create any object instances.

In other words, only the first approach creates a singleton. The second approach makes a collection of related fields at the class level.

Upvotes: 3

Related Questions