你也可以使用一个协议
protocol NotificationName {
var name: Notification.Name { get }
}
extension RawRepresentable where RawValue == String, Self: NotificationName {
var name: Notification.Name {
get {
return Notification.Name(self.rawValue)
}
}
}
然后将你的通知名定义为enum
.例如:
class MyClass {
enum Notifications: String, NotificationName {
case myNotification
}
}
像这样使用它
NotificationCenter.default.post(name: Notifications.myNotification.name, object: nil)
这样,通知名称将与基础Notification.Name
解耦.你只需要修改你的协议,以防Notification.Name
个版本的实现发生变化.