A protocol that extends CustomStringConvertible and uses reflection to add a
detailed textual representation to any class. Two styles are supported:
normal: Similar to Swift's default textual representation of structs.json: Pretty JSON representation.
Add the following to your Podfile:
pod 'ReflectedStringConvertible'
Add the following to your Cartfile:
github "mattcomi/ReflectedStringConvertible"
Simply import ReflectedStringConvertible and conform to the
ReflectedStringConvertible protocol:
import ReflectedStringConvertible
classYourClass:ReflectedStringConvertible{
// that's all.
}For example:
classPerson:ReflectedStringConvertible{varname:Stringvarage:Intinit(name:String, age:Int){self.name = name
self.age = age
}}print(Person(name: "Matt", age: 33)) outputs:
Person(name: "Matt", age: 33)
A style may be specified with reflectedDescription(style:). The default style is normal. That is, calling description is the same as calling reflectedDescription(.normal).
For example, print(Person(name: "Matt", age: 33).reflectedDescription(.json)) outputs:
{
"age" : 33,
"name" : "Matt"
}
Refer to the API Documentation for further information.
ReflectedStringConvertible objects with ReflectedStringConvertible stored properties are handled correctly:
classMovie:ReflectedStringConvertible{vartitle:Stringvaryear:Int
// another ReflectedStringConvertible
vardirector:Personinit(title:String, year:Int, director:Person){self.title = title
self.year = year
self.director = director
}}letgeorge=Person(name:"George Miller", age:71)letmovie=Movie(title:"Mad Max", year:2015, director: george)print(movie.reflectedDescription(.normal)) (or just print(movie)) outputs:
Movie(title: "Mad Max", year: 2015, director: Person(name: "George Miller", age: 71))
And print(movie.reflectedDescription(.json)) outputs:
{
"title" : "Mad Max",
"year" : 2015,
"director" : {
"age" : 71,
"name" : "George Miller"
}
}
ReflectedStringConvertible objects within Array, Dictionary and Set collections are handled correctly:
classSeries:ReflectedStringConvertible{vartitle:Stringvarcast:[Person]init(title:String, cast:[Person]){self.cast = cast
}}varcast=[Person]()
cast.append(Person(name:"Justin Theroux", age:44))
cast.append(Person(name:"Carrie Coon", age:35))letseries=Series(title:"The Leftovers", cast: cast)print(series) outputs:
TVShow(title: "The Leftovers", cast: [Person(name: "Justin Theroux", age: 44), Person(name: "Carrie Coon", age: 35)])
print(series.reflectedDescription(.json)) outputs:
{
"title" : "The Leftovers",
"cast" : [
{
"age" : 44,
"name" : "Justin Theroux"
},
{
"age" : 35,
"name" : "Carrie Coon"
}
]
}
Developed by Matt Comi (@mattcomi)