Reputation: 22926
I've been using NSRegularExpression quite a bit, and I've been thinking that it doesn't make sense that the method matchesInString()
doesn't return an optional array.
Every time I use this class, I have to check the returned [AnyObject]
array to see if it's count is > 0 before I use it.
Instead it would be much more elegant to be able to use Optional binding or check for nil if there was nothing returned.
Is this an API oversight or is there something I'm not getting?
extension NSRegularExpression {
/* The fundamental matching method on NSRegularExpression is a block iterator. There are several additional convenience methods, for returning all matches at once, the number of matches, the first match, or the range of the first match. Each match is specified by an instance of NSTextCheckingResult (of type NSTextCheckingTypeRegularExpression) in which the overall match range is given by the range property (equivalent to rangeAtIndex:0) and any capture group ranges are given by rangeAtIndex: for indexes from 1 to numberOfCaptureGroups. {NSNotFound, 0} is used if a particular capture group does not participate in the match.
*/
func enumerateMatchesInString(string: String, options: NSMatchingOptions, range: NSRange, usingBlock block: (NSTextCheckingResult!, NSMatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void)
func matchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> [AnyObject]
func numberOfMatchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> Int
func firstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSTextCheckingResult?
func rangeOfFirstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSRange
}
Upvotes: 0
Views: 327
Reputation: 131408
NSRegularExpression is a class that has been around since long before Swift existed. The contract for matchesInString:options:range:
states that it returns an array of NSTextCheckingResult
objects, where if nothing matches, there will be a single NSTextCheckingResult
object with the range {NSNotFound, 0}
.
It's a legacy thing. Objective-C doesn't have the concept of optionals.
Why don't you create your own extension to NSRegularExpression that offers a method that returns an optional, and nil if there are no matches?
Upvotes: 2