Skip to content

Instantly share code, notes, and snippets.

@tomlokhorst
Created May 27, 2015 18:00
Show Gist options
  • Save tomlokhorst/663733aa392e5dc19438 to your computer and use it in GitHub Desktop.
Save tomlokhorst/663733aa392e5dc19438 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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