Rishi
Rishi

Reputation: 2037

Test if variable is declared in a class in Swift

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

Answers (2)

newacct
newacct

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

pNre
pNre

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

Related Questions