Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift mutating func in Singleton

Tags:

ios

swift

In Swift I have this Singleton

struct Networking {
    static let shared = Networking()
    private var observed: Set<String> = []
}

I have to manipulate observed and I need to create useful method to insert and remove member in Set.

mutating func addObserver(for member: String) {
    //other code
    observed.insert(member)
}

mutating func removeObserver(for member: String) {
    //other code
    observed.remove(member)
}

The problem is when I try to call this methods like this

Networking.shared.addObserver(for: "x")

because I'm getting this error

cannot use mutating on immutable value: “shared” is a “let” constant

This error is pretty clear. shared is let and obviously it cannot be modified. But to modify the var I need to declare method as mutating. It's a vicious circle.

Any ideas? Thanks.

like image 679
Fry Avatar asked Nov 26 '25 23:11

Fry


1 Answers

If you want your Networking object to act as a singleton, why not make it a class instead of a struct?

class Networking {

    static let shared = Networking()
    private var observed: Set<String> = []

    func addObserver(for member: String) {
        //other code
        observed.insert(member)
    }

    func removeObserver(for member: String) {
        //other code
        observed.remove(member)
    }
}

Networking.shared.addObserver(for: "x")

This simplifies the code and solves your issue.

like image 172
nathangitter Avatar answered Nov 29 '25 14:11

nathangitter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!