NSRegularExpression 可选 Returns

NSRegularExpression Optional Returns

我一直在使用 NSRegularExpression,我一直认为 matchesInString() 方法没有意义 return 不是可选数组。

每次我使用这个 class 时,我都必须在使用它之前检查 returned [AnyObject] 数组以查看它的计数是否 > 0。 相反,如果没有 returned.

,则能够使用 Optional 绑定或检查 nil 会更加优雅

这是 API 的疏忽还是我没有得到什么?

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

}

NSRegularExpression 是一个 class,早在 Swift 存在之前就已经存在了。 matchesInString:options:range: 的合同声明它 returns 一个 NSTextCheckingResult 对象的数组,如果没有匹配项,将有一个 NSTextCheckingResult 范围为 {NSNotFound, 0} 的对象.

这是一个遗留问题。 Objective-C 没有可选项的概念。

你为什么不创建你自己的 NSRegularExpression 扩展,它提供了一个 returns 可选的方法,如果没有匹配则为 nil?