Little Big Detail #2: Contextual Class Names
Little Big Details are the subtle details that quicktype takes care of when turning your data into beautiful, readable code. This Little Big Detail is about how quicktype uses the names of outer types to generate nice alternate names when property type names collide.
In every programmer's life there comes a day when they have to build a Swift app that stores data about celebrities and their pets. The back-end might provide JSON data like:
{
"names": {
"given": "Daenerys Targaryen",
"nick": "Dany"
},
"job": "Khaleesi",
"hobby": "government",
"pet": {
"names": {
"given": "Rhaegal",
"nick": "Ray"
},
"species": "dragon",
"size": "huge"
}
}
Run quicktype on this data and it infers these types:
struct Celebrity {
let names: Names
let job, hobby: String
let pet: Pet
}
struct Names {
let given, nick: String
}
struct Pet {
let names: Names
let species, size: String
}
Note that quicktype inferred that the .names
and .pet.names
properties have the same type, so it created only a single Names
struct to represent both of them in the Celebrity
and Pet
structs. Easy!
The Celebrity/Pet app was a hit, so now the programmer moves on to a real estate app, where they're confronted with data like:
{
"property": {
"name": "Blandings Castle",
"info": {
"type": "Castle",
"county": "Shropshire"
}
},
"owner": {
"name": "Clarence Threepwood",
"info": {
"job": "Earl of Emsworth",
"arch-rival": "Sir Gregory Parsloe-Parsloe"
}
}
}
How should quicktype name the structs here? The two outer ones, Property
and Owner
, are obvious, but each contains an info
property with a distinct type. If they had the same type, such as with names
in the celebrity-pets app, quicktype would just name it Info
, but the info
properties have different types and therefore need different type names.
quicktype could take the easy route and name them Info1
and Info2
, or maybe Info
and OtherInfo
. Fortunately, quicktype is smarter than that and takes into account the outer types of the info
properties, suggesting PropertyInfo
for Property.info
and OwnerInfo
for Owner.info
:
struct RealEstate {
let property: Property
let owner: Owner
}
struct Owner {
let name: String
let info: OwnerInfo
}
struct OwnerInfo {
let job, archRival: String
}
struct Property {
let name: String
let info: PropertyInfo
}
struct PropertyInfo {
let type, county: String
}
Little Big Details like this are how quicktype generates code as you would have written it. Think quicktype is going a good job? Please share!