How to check if an object has a stored property?
<p>I need to check if an object's class has a member which could be used for assigning a value. Let's say there's a class:</p>

<pre><code>class MyClass: NSObject {

  var myVar : AnyObject!

  // ...
}
</code></pre>

<p>I tried this objC style but properties are a different beast in Swift and second line always returns false:</p>

<pre><code>let myClass: MyClass = MyClass()
let hasClassMember = myClass.respondsToSelector(Selector("setMyVar:"))

if hasClassMember {

  myClass.performSelector("setMyVar:", withObject: "Context" as! AnyObject)
} 
</code></pre>

<p>I assume Swift doesn't have a powerful reflection as ObjC has, but is there any solution? </p>

<p><strong>UPDATE</strong> It turns out my code works, however I have simplified it for demo purposes. The weird part is respondsToSelector stops working as soon as I change the type of myVar to be an instance of some custom class, let say ClassB. Feels it a bit magic... :)</p>

<p><strong>UPDATE2</strong> Finally I found the problem. I haven't wrote the full code, thought the problem is elsewhere, anyway, here's the full code. MyClass variable is actually a type of some other AnotherClass which implements AnotherClassProtocol</p>

<pre><code>protocol AnotherClassProtocol {
  //…
}

class AnotherClass: AnotherClassProtocol {
  //…
}

class MyClass: NSObject {

  var myVar : AnotherClass!
  // ...
}
</code></pre>

<p>This was causing myClass.respondsToSelector(Selector("setMyVar:")) always return false. It turns out the problem was because I omitted extending of  NSObject in my AnotherClass declaration. It starts working as expected after I fixed that:</p>

<pre><code>class AnotherClass: NSObject, AnotherClassProtocol {
  //…
}
</code></pre>

<p>I'm still learning Swift and thought NSObject is not needed as the compiler was not complaining and everything extend from NSObject anyway (at least in ObjC). Well, I'm glad I found this nasty bug.</p>