Our Date-iOS (pretend dating app for iOS developers only) is coming along nicely. In our previous post we used Swift’s Encodable protocol to quickly convert ‘AttractiveAndDesirableUser’ class instances straight to JSON for upload using JSONSerialization.

Now imagine we want to login and download the JSON and then decrypt our data into a shiny AttractiveAndDesirableUser class. Well for that we need to understand one other thing:

Codeable is simply a typealias for Encodable and Decodable

What I mean is that if your class conforms to encodable like ours does and conforms to decoable, which it will, then we can just go ahead and make it conform to codeable like so:


1
class AttractiveAndDesirableUser: Codeable {

Now you will get an error saying the class doesn’t conform quite yet and this is because we need a Decodable method to decode the JSON into our user class:


1
2
3
func decode(from decoder: Decoder) {
       
    }

Now that we’ve added our decode method we are fully conforming to Codable! Again, we simply give it the CodingKey enum to get to work decoding our JSON into a new AttractiveAndDesirableUser 😀


1
2
3
4
5
6
7
8
9
func decode(from decoder: Decoder) throws {
        var container = try decoder.container(keyedBy: CodeableKeys.self)
        let desirableName = try container.decode(name, forKey: .name)
        let desirableAge = try container.decode(age, forKey: .age)
        let desirableRating = try container.decode(rating, forKey: .rating)
        let desirableImage = try container.decode(profileImageURL, forKey: .profileImageURL)
        let desirableBio = try container.decode(bio, forKey: .bio)
        let desirableAttrs = try container.decode(desirableAttributes, forKey: .desirableAttributes)
    }

Now we have all the properties we need to initialise our app’s user!

So in the past two posts we’ve covered Encodable, Decodable and Codable which, when we conform to them, allow us to implement our classes in such a way that we can easily serialise and deserialise them from and into JSON.

Now let the iOS Dating being with Date-iOS… we really need an icon…