Hey everyone,
I’m wondering if this is a clean or recommended way to implement a @MainActor singleton in Swift:
@MainActor
class Singleton {
nonisolated static let a = Singleton()
nonisolated init() {
}
func updateUI() {
print("UI updated on main thread")
}
}
I noticed that if I don’t provide a custom init and just use the default one, that initializer is also nonisolated.
The problem I’m running into is that I’m trying to use dependency injection inside an actor that depends on this singleton, and I’m not sure if this pattern is correct or could lead to issues with actor isolation.
So my questions are:
→ Is this pattern considered “clean” or idiomatic when using @MainActor?
→ Is there a better approach for defining a @MainActor singleton when I also need dependency injection inside another actor?
Here’s a simplified example:
@MainActor
class Singleton { }
actor Test {
init(a: Singleton = Singleton()) { }
}
This compiles just fine.
But if I add a custom initializer:
@MainActor
class Singleton {
init() {}
}
actor Test {
init(a: Singleton = Singleton()) { }
}
Now it doesn’t compile anymore.
From what I understand, that means the custom init becomes nonisolated by default.
However, if I make the initializer explicitly nonisolated, it works again:
@MainActor
class Singleton {
nonisolated init() {}
}
actor Test {
init(a: Singleton = Singleton()) { }
}
I want to know if that’s actually a clean or safe approach.
In my case, the singleton holds shared, immutable state across the app, but its methods need to run on the main actor (for example, UI updates).
I am using swit 6 with strict concurent
Thanks!