LoginSignup
5
7

More than 5 years have passed since last update.

Notification.Nameを生やす

Last updated at Posted at 2017-07-25

Swift3あたりから徐々にNSNotificationのイベント名がNotification.Nameという構造になってきました。
そのため

NotificationCenter.default.post(Notification(name: Notification.Name("notification_name")))

という書き方が一般的になりました。

Notification.Name("notification_name")

pubsubで文字列をハードコーディングするのは怖い(送信側と購読側でtypoすると動かなくなる)ので、ミスコーディングをコンパイラに判断させるためにもNotification.Nameを自分で生やすのが良いかと思います。

extension Notification.Name {
  static var UIApplicationDidTappedStatus: Notification.Name {
    return Notification.Name(rawValue: "com.noppe.fox.notification.tapped.statusbar")
  }
}

このようにextensionを生やすことで

NotificationCenter.default.post(.init(name: .UIApplicationDidTappedStatus))

これで簡潔に、かつタイプミスの心配も無くなります。

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7