A Better Way to Sort: NSDataDetectors

Generally speaking, I’m a firm believer that the simplest way to do something—especially in regards to code—is the best way to do it. So when I found out about NSDataDetectors earlier this morning my mind was blown.

A few times over the last few weeks at Flatiron, we’ve been asked to validate data-fields for things such as email addresses, phone numbers, passwords, etc. Each time I found my self either struggling to put together a regex or, more often, fleeing to Stackoverflow to find a method that could to the validation for me. While I did learn a fair amount from this (mostly patience) often times the end result was some unwieldy hard to read chunk of code that would likely make me look like a rocket scientist to any of my friends that have never tried their hand at code before (see the below snippet of a phone number validation courtesy of zacharydrossman.com):

While according to Debuggex it works, it’s very hard to make heads or tails of what exactly is going on…even with the flowchart. Furthermore, it’s absurdly difficult to replicate from memory so you’re stuck either copy/pasting it or saving it as a snippet in Xcode. While neither of these are the end of the world, I personally like code I can call from memory and explain to people easily. That being said, here’s the same method using NSDataDetectors:

Sure it’s a few lines longer, but right of the bat it’s much easier to read and modify. The only major change in logic is that the NSDataDetector is giving me the number of occurrences for a given data type (in this case phone numbers) so I simply need an if statement stating that if the number of matches is 0 then the user did not enter a phone number into the text field as specified. Furthermore, NSTextCheckingTypePhoneNumber is already set to scan for overseas numbers. Meaning I don’t have to go through the process of making another regular expression to field those cases. The best part of this method though is that it’s easily modified to search for other data types. You can view the full list in Apple’s documentation, but some notable ones are:

  • NSTextCheckingTypeOrthography 
  • NSTextCheckingTypeDate
  • NSTextCheckingTypeAddress
  • NSTextCheckingTypeLink
  • NSTextCheckingTypeTransitInformation

Just by swapping out the NSTextCheckingTypePhoneNumber portion of the code with any of the above, the method’s function changes entirely without very much effort at all. All in all, I’d say detector methods are faster and easier to both read and write. And while I can still see some cases where one might prefer a regular expression (especially if you want to omit values that NSDataDetector will detect) for most purposes I’m hard pressed to find a reason not to use a detector method. The ease of use factor makes them pretty hard to pass up.

Leave a Reply

Your email address will not be published. Required fields are marked *