Notifications and userInfo with Swift 3.0
Original article: http://dev.iachieved.it/iachievedit/notifications-and-userinfo-with-swift-3-0/ Original author: Joe <!--Body starts here-- Notifications and userInfo with Swift 3.0 Swift 3.0 brought quite a few changes to the Swift language, including the removal of prefixes from Foundation framework types — the Great Renaming. became , became , and so on. This means the usage of — oh sorry, — with needs to be updated. This is a significant difference between Swift 2 and Swift 3. The way to get the default is now . Additionally, the model of using a selector when receiving notifications has changed to specifying a closure or function to execute. For example, in Swift 2 you would write: While in Swift 3 it's written as: The example above sets up the notification center to deliver notifications to the function, which has a method signature of . Alternatively, you can use a closure: Posting Notifications Now let's look at how to post notifications. The method from Swift 2.0 has been replaced by in Swift 3.0. takes as a parameter, which is called a dictionary literal in Swift. Note that the values in don't need to be of the same type (as indicated by the ); here a type and a type are sent together. Handling Notifications Using syntax to unwrap and validate expected data from is a great approach. To verify the behavior, try calling using a type or another object type instead of . You'll see in the console output. Sample Code You can try the code above in a simple iOS project. Create a Single View Application project and replace the contents of with the following: Key points: - A 's "name" is no longer a type but a type, so when declaring a notification, use . This allows us to use anywhere a is needed, such as in and . - It is recommended to use a separate method rather than tangled-up code blocks. That's it — clean and effective! Comments Section Improved way of declaring and using notifications: 1) First declare the notification name: 2) Post a notification using the notification name: 3) Observe the notification: