Meh. In principle, no, this is possibly bad form, but in practice I've had very good success with it, and have had to go to great contortions in code bases where I didn't do it this way. Singletons are a venerable part of Cocoa. There's a broad movement (myself included) trying to move away from them, but it's not always clear that the pain is worth it. I'm not going to make much noise about whether you should or shouldn't here, let's talk about how.
The answer is to remember that Cocoa singletons are not Singletons. They're "shared singletons." They're just some instance. So set it.
struct User {
static var sharedUser = User()
}
func decodeSomething() {
User.sharedUser = ... some decoded user ...
}
This form isn't thread safe, which can be fine. If you need it to be thread-safe you can do that in the usual ways (dispatch_sync
, dispatch_barrier_async
). And you can add a didSet
handler if you want to post a notification or notify observers some other way that the user has changed. But this whole approach works fine.
As you have more experience, you will probably decide that you hate this for some reason that you can't exactly articulate, vaguely retailed to "testability" (many of us do), and you'll come up with other solutions. But really this is fine.