Search code examples
swiftencapsulation

What is the most common way to handle string names for Notifications and UserDefaults key names


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?


Solution

  • One 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:

    class MyAppPreferences {
        static let shared = MyAppPreferences()
    
        private let highScoreKey = "highScore"
        var highScore: Int {
            get {
                return UserDefaults.standard.integer(forKey: highScoreKey)
            }
            set {
                UserDefaults.standard.set(newValue, forKey: highScoreKey)
            }
        }
    }
    

    On other code you can do this to set it:

    MyAppPreferences.shared.highScore = 100
    

    or the following to read it:

    let score = MyAppPreferences.shared.highScore
    

    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.

    class SomeClass {
        static someClassEventNotification = NSNotification.Name("someUniqueName")
    }