Is there a typesafe way to use selectors in Swift? Is there a typesafe way to use selectors in Swift? swift swift

Is there a typesafe way to use selectors in Swift?


Typesafe selectors were just released in Xcode 7.3 beta 4:

let sel = #selector(insertSubview(_:aboveSubview:)) // sel has type

Selector is now a first class citizen and comes with some nice Swift compiler warnings. If needed you can still pass in a string:

let sel = Selector("propertyName")

See a much more complete answer here: @selector() in Swift?

Xcode Release Notes: http://adcdownload.apple.com/Developer_Tools/Xcode_7.3_beta_4/Xcode_7.3_beta_4_Release_Notes.pdf


Use the Swift notion of optionals as:

if let result = object.notARealSelector?(/* args */) {   // Use Result}

where the ? used following notARealSelector with return false to if when there is no such method defined on the type of object.

There is a caveat for optional protocol requirements:

Optional protocol requirements can only be specified if your protocol is marked with the @objc attribute. Even if you are not interoperating with Objective-C, you need to mark your protocols with the @objc attribute if you want to specify optional requirements.

But since your are asking about optional methods in the first place, you must be talking about this in the Objective-C context.


You can use reflection to get the names of an object's properties as strings, as summed up in this answer, but that won't make the connection between an identifier and its string name the way @selector does in ObjC. Some creative use of reflection might work around that problem, but you might also do well to file a bug.