Created
March 25, 2019 19:30
-
-
Save NunoAlexandre/05515eff0524a7ec98669df118880dbb to your computer and use it in GitHub Desktop.
Making User FromJson compliant
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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