是否可以保证枚举具有特定的案例?

时间:2017-10-03 10:30:09

标签: swift enums

我有一个协议:

protocol ReduxTransition {}

我有一个枚举:

enum ProfileTransition: ReduxTransition {
   case authorization
   ...
   case showNotification(NotificationType)
} 

enum RatingTransition: ReduxTransition {
   case pop
   ...
   case showNotification(NotificationType)
}

我想做这样的事情,以避免使用类似的实现来显示通知

func processError(performTransition: @escaping (ReduxTransition) -> ()) {
   var notification: NotificationType!
   performTransition(.showNotification(notification))
}

1 个答案:

答案 0 :(得分:2)

如果有人有兴趣,我应用了以下解决方案:

protocol NotificationPresentable {
   static func getNotificationTransition(of type: NotificationType) -> Self
}

extension ProfileTransition: NotificationPresentable {
   static func getNotificationTransition(of type: NotificationType) -> ProfileTransition {
       return .showNotification(type)
   }
}

extension RatingTransition: NotificationPresentable {
   static func getNotificationTransition(of type: NotificationType) -> RatingTransition {
       return .showNotification(type)
   }
}

func processError<Transition: NotificationPresentable>(performTransition: @escaping (Transition) -> ()) {
   let notification: NotificationType!
   ...
   performTransition(Transition.getNotificationTransition(of: notification))
}

也许有人知道如何让这个解决方案变得更好?