Using The Swift Singleton

Using the Swift Singleton

There is a lot of info available on singletons in Swift. Have you come across this article with your Google prowess? http://krakendev.io/blog/the-right-way-to-write-a-singleton

But to answer your question, you can simply define anything you'd like to use normally.

class Singleton {
static let sharedInstance = Singleton() // this makes singletons easy in Swift
var stringArray = [String]()

}

let sharedSingleton = Singleton.sharedInstance

sharedSingleton.stringArray.append("blaaaah") // ["blaaaah"]

let anotherReferenceToSharedSingleton = Singleton.sharedInstance

print(anotherReferenceToSharedSingleton.stringArray) // "["blaaaah"]\n"

How to use the singleton pattern in conjunction with dependency injection?

  1. Could you show me how to properly use dependency injection with the singleton pattern in Swift?

    Rather than accessing ServiceSingleton.shared directly, you access an instance variable that is injected into your object, usually in the initializer if possible, otherwise as a settable property, post-initialization:

    protocol FooService {
    func doFooStuff()
    }

    class ProductionFooService: FooService {

    private init() {}

    static let shared = ProductionFooService()

    func doFooStuff() {
    print("real URLSession code goes here")
    }

    }

    struct MockFooService: FooService {
    func doFooStuff() {
    print("Doing fake foo stuff!")
    }
    }

    class FooUser {
    let fooService: FooService

    init(fooService: FooService) { // "initializer based" injection
    self.fooService = fooService
    }

    func useFoo() {
    fooService.doFooStuff() // Doesn't directly call ProductionFooService.shared.doFooStuff
    }
    }

    let isRunningInAUnitTest = false

    let fooUser: FooUser
    if !isRunningInAUnitTest {
    fooUser = FooUser(fooService: ProductionFooService.shared) // In a release build, this is used.
    }
    else {
    fooUser = FooUser(fooService: MockFooService()) // In a unit test, this is used.
    }

    fooUser.useFoo()

    Typically initialization of ViewControllers is done by your storyboards, so you can't ingect your dependancies via initializer parameters, and will have to instead use stored properties that are set after object initialization.

  2. Could you explain to me what this achieves?

    Your code is no longer coupled to ProductionFooService.shared. As a result of this, you can introduce different implementations of FooService, such as one for a beta environment, a mock one for unit testing, etc.

    If all your code pervasively directly uses your prod dependancies, you'll...

    1. find that it's impossible to instantiate your objects in a test environment. You don't want your unit tests, CI test environments, beta environments, etc. connecting to prod databases, services and APIs.

    2. Have no true "unit" tests. Every test will be testing a unit of code, plus all of the common dependancies that it transitively depends on. If you were to ever make a code change to one of these dependancies, it would break most of the unit tests in your system, which makes it harder to pin down exactly what failed. By decoupling your dependancies, you can use mock objects that do the bare minimum necessary to support a unit test, and ensure that each test is only testing a particular unit of code, and not the transitive dependancies it relies on.

  3. Should I always use DI when I use the singleton pattern in my iOS projects from now on?

    It's a good habit to pick up. Of course, there are qucik-and-dirty-projects for which you just want to move fast and won't really care, but it'll surprise you how many of these supposed qucik-and-dirty-projects actually take off, and pay the cost down the road. You just need to be cognizant of when you're hindering yourself by not taking some extra time to decouple your decencies.

Swift - Singleton without global access

You can use an atomic flag (for thread safety) to mark the singleton as being instantiated:

class Singleton {

static private var hasInstance = atomic_flag()

init() {
// use precondition() instead of assert() if you want the crashes to happen in Release builds too
assert(!atomic_flag_test_and_set(&type(of: self).hasInstance), "Singleton here, don't instantiate me more than once!!!")
}

deinit {
atomic_flag_clear(&type(of: self).hasInstance)
}
}

You mark the singleton as allocated in init, and you reset the flag in deinit. This allows you on one hand to have only one instance (if the original instance doesn't get deallocated), and on the other hand to have multiple instances, as long as they don't overlap.

App code: assuming that you'll keep a reference to the singleton, somewhere, that you inject downstream, then deinit should never be called, which leads to only one possible allocation.

Unit testing code: if the unit tests properly do the cleanup (the tested singleton gets deallocated after every test), then there will be only one living instance at a certain point in time, which won't trigger the assertion failure.

Swift singleton vs. static properties/methods

To me, a simpler alternative would be to convert all properties and methods to static, and drop the sharedInstance property.

These do not do the same thing. The recommended approach is not actually a singleton at all. It's just a well-known instance. The concept of the Singleton pattern is that there must only be one instance. The concert of the shared instance pattern is that there can be more than one instance, but there is one that you probably want, and you would like easy access to it.

The advantage of shared instances is that they are not magical. They're just instances. That means that they can be handed around as values. They can be replaced with other instances that may be configured differently. They are easier to test (because they can be passed into functions).

True singletons are a very rigid pattern that should only be used when it is absolutely necessary that no other instance exist, usually because they interact with some external unique resource in a way that would create conflicts if there were multiples (this is pretty rare). Even in this case, in Swift, you should generally just make init private to prevent additional instances being created.

If you look around Cocoa, you'll find that shared instances are extremely common for things that would be Singletons in other frameworks, and this has been very powerful. For instance, there is a well known NotificationCenter called default, and it's probably the only one you've ever used. But it's completely valid to create a private NotificationCenter that's independent (I've actually done this in production code).

The fact that UIDevice.current is how you access the device, rather than static methods, leaves open the possibility of new APIs that can handle multiple devices (it also helps with unit testing). In the earliest versions of iOS, the only UIScreen was .main, and it might have made sense to make it a singleton. But because Apple didn't, when mirroring was added in 4.3, it was simple to talk about the second screen (UIScreen.mirrored). You should generally be very slow to assume that there can only be one of something.

Delegation of singleton class in Swift

First, I'd like to point to:

1- Creating a singleton Class should contains:

private init() {}

That leads to enforce to access the class only by using its shared instance.

2- As mentioned in Max's Answer, the delegate should be optional and has a weak reference.

3- The protocol should be a type of class, as follows:

protocol AClassDelegate: class

For more information, you might want to check this Q&A.


Now, let's assume -for testing purposes- that the method1() from AClassDelegate should be get called when calling foo() from A class:

protocol AClassDelegate: class {
func method1()
}

class A {
private init() {}
static let shared = A()

weak var delegate: AClassDelegate?

func foo() {
print(#function)

delegate?.method1()
}
}

Let's implement classes that conforms to AClassDelegate:

class B: AClassDelegate {
func bar() {
A.shared.delegate = self
A.shared.foo()
}

func method1() {
print("calling the delegate method B Class")
}
}

class C: AClassDelegate {
func bar() {
A.shared.delegate = self
A.shared.foo()
}

func method1() {
print("calling the delegate method C Class")
}
}

Output should be:

let b = B()
b.bar()
// this will print:
/*
foo()
calling the delegate method B Class
*/

let c = C()
c.bar()
// this will print:
/*
foo()
calling the delegate method C Class
*/

Using Arrays in Singleton Class in iOS

Array in swift is implemented as Struct, which means Array is a value type and not a reference type. Value types in Swift uses copy on write (COW) mechanism to handle the changes to their values.

So in your ViewController when you assigned

var PetArray = PetInfo.shared.petArray

your PetArray was still pointing to the same array in your PetInfo.shared instance (I mean same copy of array in memory) . But as soon as you modified the value of PetArray by using

PetArray.append(pet)

COW kicks in and it creates a new copy of petArray in memory and now your PetArray variable in your ViewController and PetInfo.shared.petArray are no longer pointing to same instances instead they are pointing to two different copies of array in memory.

So all the changes you did by using PetArray.append(pet) is obviously not reflected when you access PetInfo.shared.petArray in secondViewController

What can I do?

remove PetArray.append(pet) and instead use PetInfo.shared.petArray.append(pet)

What are the other issues in my code?

Issue 1:

Never use Pascal casing for variable name var PetArray = PetInfo.shared.petArray instead use camel casing var petArray = PetInfo.shared.petArray

Issue 2:

class PetInfo {

static let shared: PetInfo = PetInfo()

lazy var petArray: [PetInfo] = []
var PetID:Int
var PetName:String
...

init(){ .. }
}

This implementation will not ensure that there exists only one instance of PetInfo exists in memory (I mean it cant ensure pure singleton pattern), though you provide access to instance of PetInfo using a static variable named shared there is nothing which stops user from creating multiple instances of PetInfo simply by calling PetInfo() as you did in let pet = PetInfo()

rather use private init(){ .. } to prevent others from further creating instances of PetInfo

Issue 3:

You are holding an array of PetInfo inside an instance of PetInfo which is kind of messed up pattern, am not really sure as to what are you trying to accomplish here, if this is really what you wanna do, then probably you can ignore point two (creating private init) for now :)

Protocol defining singleton with properties

Make the protocol available only for classes (struct won't be able to conform to this protocol):

protocol SingletonProtocol: AnyObject {
static var shared: SingletonProtocol { get }
var variable: Int { get set }
}

Now you can set the shared property as a let

class Singleton: SingletonProtocol {
static let shared: SingletonProtocol = Singleton()
var variable: Int = 0
}


Related Topics



Leave a reply



Submit