Skip to content

Serializing

Brian Mullen edited this page Apr 30, 2018 · 4 revisions

There are 2 protocols (Serializable and IndexSerializable) you can use for serializing.

All the examples will use the following struct:

struct User {
     var id: Int
     var name: String
     var email: String
}

Serializable

extension User: Serializable {
     func serialized() -> [String: Any] {
          return [
               "id": id,
               "name": name,
               "email": email
          ]
     }
}

IndexSerializable

extension User: IndexSerializable {
     func serialized() -> [Any] {
          return [id, name, email]
     }
}

Which one should you use?

Which one you use depends on your preference or the data structure you need.

What about Reflection?

Now, you might be thinking "but couldn't I use reflection to do this for me automagically?" You could. And if you're into that, there are some other great frameworks for you to use. But Outlaw believes mirrors can lead down the road to a world of hurt. Outlaw lives in a world where What You See Is What You Get™, and you can easily adapt to APIs that snake case, camel case, or whatever case your backend developers are into. Outlaw code is explicit and declarative. But don't just take Outlaw's word for it—read the good word towards the end here on the official Swift blog.

Clone this wiki locally