What is the most common way to handle string names

2019-05-30 16:12发布

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?

3条回答
We Are One
2楼-- · 2019-05-30 16:41

The common approach is creating

struct Constants { 
   static let key1 = "value1"
   static let key2 = "value2"
   .....
}

// for notifications

extension Notification.Name {
  static let didReceiveData = Notification.Name("didReceiveData")
  static let didCompleteTask = Notification.Name("didCompleteTask")
}

some guys prefer global variables with ( k letter prefix )

let kDomain = "value1"

dates to #define in Objective-C , but using Constants is a clean way to code readers

查看更多
做自己的国王
3楼-- · 2019-05-30 16:44

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")
}
查看更多
成全新的幸福
4楼-- · 2019-05-30 17:02

I think using enum is more appropriate way to define constants

User Defaults:

class MyAppPreferences {
    static let shared = MyAppPreferences()

    private enum Key: String {
        case userName
        case email
    }

    var userName: String? {
        get {
            return UserDefaults.standard.string(forKey: Key.userName.rawValue)
        }
        set {
            UserDefaults.standard.set(newValue, forKey: Key.userName.rawValue)
        }
    }
}

Notification:

enum AppNotification: String {
    case didReceivedData
    case didCompleteTask
}

extension Notification.Name {
    init(_ appNotification:AppNotification) {
        self.init(appNotification.rawValue)
    }
}

//Use:

func notify() {
    NotificationCenter.default.post(.init(name: .init(.didReceivedData)))
} 
查看更多
登录 后发表回答