I will be using a few string names throughout my app for my Notifications and UserDefault names.
I have heard that for type safety it's a good practice to define your notification
names or UserDefaults
key names as static strings and make them part of a class or struct.
What is the most common way to handle string names for your Notification and UserDefault names?
I have thought about putting them in my AppDelgate class as global variables as follow...
let MY_STRING_NAME = "My string name"
class AppDelegate: UIResponder, UIApplicationDelegate {}
/// Then just use MY_STRING_NAME in other classes.
Or
class SomeClass {
let myStringName:String = "My string name"
}
/// Then use myClassInstance.myStringName
What is the best approach?
The common approach is creating
// for notifications
some guys prefer global variables with ( k letter prefix )
dates to
#define
in Objective-C , but using Constants is a clean way to code readersOne option for UserDefaults is to create a helper class that hides the fact that you are using UserDefaults. This makes it appear to the rest of your code just like you are using a simple class and its properties.
Something like this:
On other code you can do this to set it:
or the following to read it:
Add a computed property and private key for each app preference needed in your app. This makes the rest of your code much cleaner.
And in for some reason you need to change how one or more of the preferences are stored in the future, you only need to change the code in one place.
For notification names, you can add constants to each class the notification is associated with. You see this pattern in many iOS classes such as UIApplication, UITextView, and others.
I think using enum is more appropriate way to define constants
User Defaults:
Notification: