Codable protocol in Swift 4 + extension

When Swift 4 went out and we finally had a chance to play with it in a playground, I began reading this article on Ray Wenderlich's site : https://www.raywenderlich.com/163857/whats-new-swift-4   I was particularly interested in this part about the new Codable protocol : [crayon-5a16c29796102668530808/] As you can see, it's a pretty interesting (and simple) way to convert a Codable into a String (a stringified version of a JSON dictionary).   I also read this article from Natasha-The-Robot's weekly newsletter : https://cur.at/hxKamEa?m=email&sid=QSej7qn This is interesting: the author creates a new protocol (Serializable) to let the Codable-conforming object encode itself to Data. [crayon-5a16c2979610f394569458/]   Well, as far as I'm concerned, I often have to parse a JSON dictionary (a.k.a. a Dictionary<String, Any>), or create a JSON dictionary from an object, not a String or a Data. So, this is my implementation of this Serializable protocol idea : [crayon-5a16c29796115179899201/]   The JSONCodable protocol now has two required methods :

  • a function allowing the Serializable-conforming object to convert itself a JSON

Tagged , Read More

A concrete example of the « guard » statement in Swift 2

Background

A lot of my recent project involve functions with completion handlers returning either an error, or an (optional) object. That's the case for most of CloudKit functions. Example: [crayon-5a16c297981c6874678202/] Or MapKit : [crayon-5a16c297981ce800767484/] I'm still learning the new error handling in Swift 2, so I don't know if these completionHandlers returning NSError? still have a future. What I know is that the guard statement is quite helpful in this case. (suite…)

Tagged , Read More

Structure your UITableView better with structs and enums in Swift

In this post, I present a technique I use a lot when building a UITableViewController in Swift, but which I haven't seen used by many other people very often.

Background

This technique was inspired by this years's edition of the legendary Stanford CS193p on iTunes U (presented by the just as legendary Paul Hegarty) : iTunes U - Developing iOS 8 apps with Swift, and by this M2M site which for years now has specialized on giving unofficial solutions to the assignments (I suppose that Stanford students have a chance of having their work corrected, but there is no "official" solution to the assignments for the iTunes U followers). In this course, the 4th assignment dealt specifically with table views. Namely, one of the requirements was:
While you might be tempted to deal with this with large if-then or switch statements in your UITableViewDataSource and navigation methods, a cleaner approach would

Tagged , , Read More