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:
class MyClass: NSObject {
var myVar : AnyObject!
// ...
}
I tried this objC style but properties are a different beast in Swift and second line always returns false:
let myClass: MyClass = MyClass()
let hasClassMember = myClass.respondsToSelector(Selector("setMyVar:"))
if hasClassMember {
myClass.performSelector("setMyVar:", withObject: "Context" as! AnyObject)
}
I assume Swift doesn't have a powerful reflection as ObjC has, but is there any solution?
UPDATE 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... :)
UPDATE2 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
protocol AnotherClassProtocol {
//…
}
class AnotherClass: AnotherClassProtocol {
//…
}
class MyClass: NSObject {
var myVar : AnotherClass!
// ...
}
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:
class AnotherClass: NSObject, AnotherClassProtocol {
//…
}
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.
selector()
around thesetMyVar:
as it isn't needed.hasClassMember
was also true/false based on the property name – Paulw11