1

I have a global stuct where I am keeping a few properties that are used throughout. Some of the properties need to be mutable.

Here's what I'm doing:

public struct AppGlobal {

    static let someManager = PrayerManager()
    static var currentUser = UserModel()
    static var cache = UserCache()

    // Prevent others from initializing singleton
    private init() { }
}

This way, I can do AppGlobal.currentUser.prop1 = 5. Is it still singleton and safe if I set those static properties to var instead of let?

TruMan1
  • 33,665
  • 59
  • 184
  • 335
  • Ah, didn't see *struct*. Yeah, I think that's acceptable.. – Cameron Askew Mar 03 '16 at 02:34
  • You could alternatively make it a class instead of a struct, and then it could be a `let` – Cameron Askew Mar 03 '16 at 02:34
  • you really don't need to set it to var as based on your code your are changing the value of currentUser's properties and not the currentUse variable itself. Your init is private so that makes it a singleton. – Christian Abella Mar 03 '16 at 02:34
  • I tried changing it to `let` and gave a compile error saying: `Cannot assign to property: 'currentUser' is a 'let' constant`. I change `AppGlobal` to a `class` and it gave some issues when change to `let`. I have `getters/setters` for properties of `UserModel` if this is the problem? – TruMan1 Mar 03 '16 at 02:38
  • 1
    But then again, you might want the behavior of a struct instead of a class (http://stackoverflow.com/questions/24232799/why-choose-struct-over-class/24232845), in which case I think what you're doing is fine. – Cameron Askew Mar 03 '16 at 02:38
  • 1
    I'm guessing it's that `UserModel` is also a struct. So I think first you should decide if you want to use a struct or a class. – Cameron Askew Mar 03 '16 at 02:39
  • The bigger issue here is probably that you shouldn't make these types of things singletons. But for a simple app, you're probably fine. – Cameron Askew Mar 03 '16 at 02:42
  • Ah @CameronAskew you're right! `UserModel` is a struct which is why it was tripping on `var currentUser`. Thx! – TruMan1 Mar 03 '16 at 02:43
  • You can use *final class* which will give you performance similar to a struct. Then instead of static, you can use *class var* which is the class variation of static. – Dan Beaulieu Mar 03 '16 at 02:47

0 Answers0