Skip to content

Instantly share code, notes, and snippets.

@toohotz
Last active March 17, 2016 21:08
Show Gist options
  • Save toohotz/67be241b7563179497cc to your computer and use it in GitHub Desktop.
Save toohotz/67be241b7563179497cc to your computer and use it in GitHub Desktop.
Example of how to use Swift Reflection API against object property values
/*
Initialized variables to defaults to avoid having to create
initializers to keep things simple.
*/
class Superuser {
var canUseSudo: Bool = false
}
class User: Superuser {
var name: String = ""
var address: String = ""
var age: Int = 0
}
func isPersonValid(person: User) -> String?
{
var stringValue: String?
let mirrorPerson = Mirror(reflecting: person)
mirrorPerson.children.forEach { (property) in
if (property.value as? String)?.isEmpty == true || (property.value as? Int) == 0 {
stringValue = property.label // The label here will be the property's name
}
}
return stringValue
}
func isSuperPersonValid(person: User) -> String?
{
var stringValue: String?
guard let superUserMirror = Mirror(reflecting: person).superclassMirror() else { return "Cannot reflect superclass \(person.dynamicType)"
}
superUserMirror.children.forEach { (property) in
if (property.value as? Bool) == true {
stringValue = property.label
}
}
return stringValue
}
let john = User()
john.address = "Somewhere in Neverland"
john.age = 24
john.canUseSudo = true
let validationString = isPersonValid(john)
if validationString != nil {
print("Property not valid for \(validationString!)")
}
let sudoValidation = isSuperPersonValid(john)
if sudoValidation != nil {
print("This user is trying to be all powerful. This isn't right..")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment