NSNotificationCenter and Selectors in Swift

Selectors are a native type in Objective-C (SEL). Not so in Swift, where the type is currently represented by what amounts to a String (technically the type is Selector, but in actual use it is currently indistinguishable from a regular String).

Objective-C benefits from this primarily in Xcode — the compiler is able to both provide autocomplete for most selectors and to warn when it can’t find a selector. Swift has neither of these, and it’s very easy to accidentally omit a trailing : or make a typo, both of which lead to a method not found crash. Hopefully this changes someday (radar #24119236).

Another subtle pitfall with Swift selectors

Can you spot the problem with this code? Swift veterans likely will be able to, but it’s a lesson learned from experience. The compiler will not issue a warning.

Despite the notification observer being added only a few lines above, Swift’s access control, combined with the move away from dynamic dispatching, will prevent NSNotificationCenter from calling _externalStoreChanged:. It can’t see the method as it’s written and needs the scope changed to public or the dynamic keyword added. The reason here being that NSNotificationCenter is Objective-C code and, since it relies on dynamic dispatching to work, the method needs to be discoverable by it.