Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Json model vs Domain model
/* Domain model */
// A Profile consists of a person name and an optional avatar
struct Profile {
let personName: PersonName
let avatarURL: NSURL?
}
// These are the UX rules for showing a greeting:
// 1. When last name is available, greeting should be: "Hello John Smith."
// 2. When only first name is available, greeting should be: "Hi John!"
enum PersonName {
case FirstName(String)
case FullName(String, String)
var greeting: String {
switch self {
case .FirstName(let first):
return "Hi \(first)!"
case .FullName(let first, let last):
return "Hello \(first) \(last)."
}
}
}
/* Json model */
// This is the json data returned by an API.
// The `profile` property maps this json to the domain model.
// It contains all the custom logic supplied by the API developers.
//
// Example JSON:
// {
// "FirstName": "Tom",
// "AvatarURL": "http://example.com",
// "UseAvatar: false
// }
//
// The JSON parser for this type is generated by swift-json-gen.
struct ProfileJson {
let FirstName: String
let LastName: String?
let UseAvatar: Bool
let AvatarUrl: String?
var profile: Profile {
// These are the business rules for handeling the JSON data:
// 1. FirstName is always available
// 2. LastName is sometimes available
// 3. When UseAvatar == false, ignore the url
// 4. If AvatarUrl is not a real url, ignore it
let name: PersonName
if let last = LastName {
name = PersonName.FullName(FirstName, last)
}
else {
name = PersonName.FirstName(FirstName)
}
let avatarURL: NSURL?
if let url = AvatarUrl where UseAvatar {
avatarURL = NSURL(string: url)
}
else {
avatarURL = nil
}
return Profile(personName: name, avatarURL: avatarURL)
}
}
@tomlokhorst

This comment has been minimized.

Show comment Hide comment
@tomlokhorst

tomlokhorst May 27, 2015

Accompanying blog post: Swift + JSON with code generation

Owner

tomlokhorst commented May 27, 2015

Accompanying blog post: Swift + JSON with code generation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment