Reputation: 2037
I am trying to do something like this. I want to test if a class has a variable of a given name or not.
if(classInstance.hasProperty(test))
In the example I want to test if test named variable is a member of the class. Is there any way I can do it?
Upvotes: 2
Views: 698
Reputation: 122489
Modified version of @pNre's solution without looping through all ivars:
func hasProperty (obj: AnyObject, property: String) -> Bool {
return property.withCString {
class_getInstanceVariable(obj.dynamicType, $0) != nil
}
}
Upvotes: 2
Reputation: 5376
Right now there isn't a pure Swift way of doing this (reflect
isn't enough), maybe objc runtime methods can help. Using class_copyIvarList
:
func hasProperty (obj: AnyObject, property: String) -> Bool {
var count: UInt32 = 0
var ivars: UnsafeMutablePointer<Ivar> = class_copyIvarList(obj.dynamicType, &count)
for i in 0..<count {
let name = NSString(CString: ivar_getName(ivars[Int(i)]), encoding: NSUTF8StringEncoding)
if name == property {
return true
}
}
return false
}
Usage:
public class R {
private var aVar = "Hi"
private var anotherVar: Int = 0
}
hasProperty(R(), "anotherVar") // outputs true
Upvotes: 2