Leem.fin Leem.fin - 2 months ago 20
iOS Question

thread safety for getter and setter in singleton

I have created an simple singleton in Swift 3:

class MySingleton {
private var myName: String
private init() {}
static let shared = MySingleton()

func setName(_ name: String) {
myName = name
}

func getName() -> String {
return myName
}
}


Since I made the
init()
private , and also declared
shared
instance to be
static let
, I think the initializer is thread safe. But what about the getter and setter functions for
myName
, are they thread safe?

Answer Source

You are correct that those getters that you've written are not thread safe. In Swift, the best way to achieve this at the moment is using a serial dispatch queue as a locking mechanism.

class MySingleton {

    static let shared = MySingleton()

    // Serial dispatch queue
    private let lockQueue = DispatchQueue(label: "MySingleton.lockQueue")

    private var _myName: String
    var myName: String {
        get {
            var result: String!

            lockQueue.sync {
                result = self._myName
            }

            return result
        }

        set {
            lockQueue.sync {
                self._myName = newValue
            }
        }
    }

    private init() {
        _myName = "initial name"
    }
}