There is no real Swift replacement.
You can check in the following way:
someObject.someMethod?()
This calls the method someMethod
only if it's defined on object someObject
but you can use it only for @objc
protocols which have declared the method as optional
.
Swift is inherently a safe language so everytime you call a method Swift has to know the method is there. No runtime checking is possible. You can't just call random methods on random objects.
Even in Obj-C you should avoid such things when possible because it doesn't play well with ARC (ARC then triggers warnings for performSelector:
).
However, when checking for available APIs, you can still use respondsToSelector:
, even if Swift, if you are dealing with NSObject
instances:
@interface TestA : NSObject
- (void)someMethod;
@end
@implementation TestA
//this triggers a warning
@end
var a = TestA()
if a.respondsToSelector("someMethod") {
a.someMethod()
}
NSClassFromString
andrespondsToSelector
among other mechanics for checking for newly implemented functionality, I've got to believe that the mechanisms either are in place already, or will be there before release. Try watching theAdvanced Interop...
video from WWDC. – David Berry Jun 11 '14 at 16:35if #available(...)
in Swift 2.x to avoid usingrespondsToSelector
in the first place. But you knew that. (apple.co/1SNGtMQ) – GoZoner Nov 20 '15 at 23:43