NSRegularExpression可选返回

时间:2015-04-04 17:24:11

标签: regex cocoa swift optional nsregularexpression

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

每次我使用这个课时,我都要检查返回的[AnyObject]数组,看看它的计数是否为>在我使用之前0。 相反,如果没有返回任何内容,能够使用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

}

1 个答案:

答案 0 :(得分:2)

NSRegularExpression是一个在Swift存在之前就存在的类。 matchesInString:options:range:的合同规定它返回一组NSTextCheckingResult个对象,如果没有匹配,则会有一个NSTextCheckingResult个对象,其范围为{NSNotFound, 0}

这是遗产。 Objective-C没有选项的概念。

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