3

The UserDefaults.init(suiteName:) initializer is a failable initializer. However, the documentation does not specify the circumstances under which it will return a nil UserDefaults object.

Firstly, what are the circumstances under which it will return a nil UserDefaults object?

Secondly, am I safe to force-unwrap it in the context of an iPhone and iPad application?

Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
  • 3
    Use `UserDefaults.globalDomain` for the `suiteName` and it seems to return nil value. In the doc, it's states that's an invalid param, as the bundle id, I guess that passing the bundle id might fail also. – Larme Apr 16 '21 at 11:00
  • 2
    Perfect. I missed that in the `suiteName` parameter description. Now that I re-read it, it makes sense. So if I pass in a value which is not my app's main bundle identifier nor [globalDomain](https://developer.apple.com/documentation/foundation/userdefaults/1407355-globaldomain), I guess I'm okay to assume that I'll get out a non-nil `UserDefaults` object. – Adil Hussain Apr 16 '21 at 12:51

1 Answers1

1

The UserDefaults.init(suiteName:) initializer will return a nil UserDefaults object if it is passed the app's main bundle identifier or globalDomain. If you're passing in any other value, it is my guess that you're okay to assume that this initializer will return a non-nil UserDefaults object.

(Thank you to @Larme for his/her comment under my question.)

Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
  • So I assume it is safe to write `let current = UserDefaults.init(suiteName: XXX)!` with force cast which XXX is an user identifier ? – Zigii Wong Jan 14 '23 at 20:19
  • Yes, the force unwrap is fine as long as `XXX` is not your app's main bundle identifier or [globalDomain](https://developer.apple.com/documentation/foundation/userdefaults/1407355-globaldomain). – Adil Hussain Jan 15 '23 at 22:55