Trying to write a convenience toString()
method that lists all properties and their assigned values of an object.
class FooModel
{
func toString() -> String
{
var result = "[\(String(describing: type(of: self))) "
let mirror = Mirror(reflecting: self)
mirror.children.forEach
{
child in
result += "\(child.label): \(child.value), "
}
return "\(result)]"
}
}
class FooProject : FooModel
{
var id = 0
var name = ""
var announcement:String?
var showAnnouncement = false
var isCompleted = false
var completedOn:String?
var suiteMode = 0
var url = ""
}
Output:
[FooProject Optional("id"): 0, Optional("name"): , Optional("announcement"): nil, Optional("showAnnouncement"): false, Optional("isCompleted"): false, Optional("completedOn"): nil, Optional("suiteMode"): 0, Optional("url"): , ]
First, it doesn't list the actual values but the default values. Why is that? Second, is there a way to get rid of the Optional
encapsulation?
Aucun commentaire:
Enregistrer un commentaire