Giter Club home page Giter Club logo

swiftsingleton's Introduction

SwiftSingleton

tl;dr: Use the class constant approach if you are using Swift 1.2 or above and the nested struct approach if you need to support earlier versions.

An exploration of the Singleton pattern in Swift. All approaches below support lazy initialization and thread safety.

Issues and pull requests welcome.

Approach A: Class constant

class SingletonA {
    
    static let sharedInstance = SingletonA()
    
    init() {
        println("AAA");
    }
    
}

This approach supports lazy initialization because Swift lazily initializes class constants (and variables), and is thread safe by the definition of let.

Class constants were introduced in Swift 1.2. If you need to support an earlier version of Swift, use the nested struct approach below or a global constant.

Approach B: Nested struct

class SingletonB {
    
    class var sharedInstance: SingletonB {
        struct Static {
            static let instance: SingletonB = SingletonB()
        }
        return Static.instance
    }
    
}

Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier, and still works as a workaround for the lack of static constants and variables in functions.

Approach C: dispatch_once

The traditional Objective-C approach ported to Swift.

class SingletonC {
    
    class var sharedInstance: SingletonC {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: SingletonC? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = SingletonC()
        }
        return Static.instance!
    }
}

I'm fairly certain there's no advantage over the nested struct approach but I'm including it anyway as I find the differences in syntax interesting.

swiftsingleton's People

Contributors

fegabe avatar hpique avatar jeehut avatar nilstack avatar solomon23 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swiftsingleton's Issues

Singleton with parameters?

Great article!
I would like to ask you: do you have some clever solution for a Singleton to which we need to pass parameters? Let's say URL and APIKey? Solution with class constant doesn't work due to initialization order. Which approach would you suggest?

Private init

Hi, first of all thanks you very much for this repo, I found it very useful. Just, I wonder if class constant approach could be incomplete. Isn't necessary a private init? with this current implementation you could create several references of the same class, with a private init you only could create one instance (the static property).

Thanks.

Swift 3

Can you provide this code for Swift 3

Using structs instead of classes?

Hi, I came along this interesting repo, as I was looking for the best way to implement a singleton pattern in Swift. As Swift also supports static properties (called Type properties in the Apple documentation) for structs, I'm just wondering if this would be an even better solution? The advantage I'm seeing is that structs - as opposed to classes - also allow to define static variables directly, so there is no need to define a constant like "sharedInstance", the struct itself could serve for this purpose. And as long as you don't define any non-static members, it would still be a singleton. Or am I missing something here?

EDIT: I think I can answer myself: The struct approach would not allow to pass the struct over in method calls, as it is possible with the .sharedInstance singleton instance of the class. And if a shared instance of the struct would be created, it would be handed over as a value type, hence effectively copying it instead of referencing it. Am I right?

Best approach changes with Swift 1.2!?

I just read through the Release notes of XCode 6.3b1 which states the following:

“static” methods and properties are now allowed in classes (as an alias for “class final”). You are now allowed to declare static stored properties in classes, which have global storage and are lazily initialized on first access (like global variables).

If I understand this correctly, then this should change both the syntax of A and the overall recommendation to A. What do you think?

I can't try it out myself right now but will have a look at it later if no one else does.

Private Initializer/Final Class

Hi,

Can we add private initializer(as below) in each of the class definition to ensure that one cannot invoke the default initializer.

private init()
{

}

Also we can make the class as final to ensure that one cannot extend the class ?

Thanks

@nonobjc solution for pure Swift codebase

In a pure Swift codebase I use the following approach to deal with a singleton extension

extension DataContext {

    @nonobjc
    static let sharedInstance = DataContext()

    @nonobjc
    static let sharedInstanceComputed : DataContext = {
        let c = DataContext()
        c.name = "Singleton Context"
        return c
    }() //define-and-call is A-OK too
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.