Skip to content

Instantly share code, notes, and snippets.

@NunoAlexandre
Created March 25, 2019 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NunoAlexandre/05515eff0524a7ec98669df118880dbb to your computer and use it in GitHub Desktop.
Save NunoAlexandre/05515eff0524a7ec98669df118880dbb to your computer and use it in GitHub Desktop.
Making User FromJson compliant
extension User: FromJson {
static func from(value: JsonValue) -> User? {
return value.ifObject { json in
User(
id: try json .! "id",
name: try json .! "name",
email: json .? "email",
country: json .? "country",
subscription: try json .! "subscription",
favouriteSongs: (json ..? "favouriteSongs") ?? []
)
}
}
}
// That's all you need for String/Int RawRepresentable Enums!
extension Subscription: FromJson {}
// Or you get to say how it's done!
// In this case, the country in JSON is short-coded and
// thus needs to be translated to the right Country case.
extension Country: FromJson {
static func from(value: JsonValue) -> Country? {
return value.ifString { str in
switch str {
case "nl": return .netherlands
case "pt": return .portugal
default: return nil
}
}
}
}
extension Song: FromJson {
static func from(value: JsonValue) -> Song? {
return value.ifObject { json in
Song(
name: try json .! "name",
band: try json .! "band"
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment