Skip to content

Instantly share code, notes, and snippets.

@koher
Created March 8, 2017 07:59
Show Gist options
  • Save koher/7bd185dcc8d5e2266e17ec5b33fb4ade to your computer and use it in GitHub Desktop.
Save koher/7bd185dcc8d5e2266e17ec5b33fb4ade to your computer and use it in GitHub Desktop.
// Argo
struct User {
  let id: Int
  let name: String
  let email: String?
  let role: Role
  let companyName: String
  let friends: [User]
}

extension User: Decodable {
  static func decode(_ json: JSON) -> Decoded<User> {
    return curry(User.init)
      <^> json <| "id"
      <*> json <| "name"
      <*> json <|? "email" // Use ? for parsing optional values
      <*> json <| "role" // Custom types that also conform to Decodable just work
      <*> json <| ["company", "name"] // Parse nested objects
      <*> json <|| "friends" // parse arrays of objects
  }
}
// Himotoki
struct Group: Decodable {
    let name: String
    let floor: Int
    let locationName: String
    let optional: [String]?

    // MARK: Decodable

    static func decode(_ e: Extractor) throws -> Group {
        return try Group(
            name: e <| "name",
            floor: e <| "floor",
            locationName: e <| [ "location", "name" ], // Parse nested objects
            optional: e <||? "optional" // Parse optional arrays of values
        )
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment