2016-08-10 2 views
1

Ich habe mehrere notifications in einem View Controller, und möchten ihre Namen halten in einem Enum:Instanzen von Notification.Name in einem Swift Enum

enum KeyboardNotifications : Notification.Name{ 
     case didAppear = Notification.Name(rawValue:"cfisher.keyboardDidAppear") 
    } 

Leider ist dies nicht funktioniert, und ich bekomme ein Kompilierfehler: raw value for enum case must be a literal value.

Gibt es das überhaupt?

Ich verwende Swift 3, BTW

+0

Mit Ihrer Erweiterungsmethode von http://stackoverflow.com/questions/38883162/implementing-expressiblebystringliteral-in-swift-3-0, 'case didAppear =" cfisher.keyboardDidAppear "' würde kompilieren. Es scheint, dass Sie Ihre eigene Frage beantwortet haben :) –

+0

Der Compiler machte mich verrückt und ich dachte, dass ich den falschen Ansatz hatte. Vielen Dank! :-) – cfischer

Antwort

3

Auf diese Weise

enum Notes: String { 

     case note1 = "note1" 
     case note2 = "note2" 

     var notification : Notification.Name { 
      return Notification.Name(rawValue: self.rawValue) 
     } 
    } 

    class ViewController: UIViewController { 

     override func viewDidLoad() { 
      super.viewDidLoad() 

      NotificationCenter.default.post(name: Notes.note2.notification ,object: nil, userInfo: nil) 
     } 
    } 
0

Eine Abhilfe wäre die Benachrichtigungen in einem struct werden zu speichern.

Um das Lesen/Löschen von Code zu erleichtern, können Sie einen globalen func zum Posten von Benachrichtigungen verwenden.

struct KeyboardNotifications { 
    static let didAppear = "cfisher.keyboardDidAppear" 
    static let didSomethingElse = "cfisher.keyboardDidSomethingElse" 
} 

func postNotification(_ aName: String, 
         object anObject: Any?, 
         userInfo aUserInfo: [AnyHashable : Any]? = nil) { 

    NotificationCenter.default.post(name: Notification.Name(rawValue: aName), 
            object: anObject, 
            userInfo:aUserInfo) 
} 

Posting-Benachrichtigungen werden wie folgt aussehen:

postNotification(KeyboardNotifications.didAppear, object: nil) 

Diese Lösung setzt voraus, dass Sie nur NotificationCenter auf den Standard veröffentlichen.