我一直在使用NSRegularExpression,我一直认为matchesInString()方法不返回可选数组是没有意义的。
每次使用这个类时,我都必须检查返回的[AnyObject]数组,看看它的计数是否大于0,然后再使用它。相反,如果没有任何返回,则可以使用可选绑定或检查为零,这样就更优雅了。
这是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
}发布于 2015-04-04 17:33:01
NSRegularExpression是一个早在Swift存在之前就已经存在的类。matchesInString:options:range:的契约声明它返回一个NSTextCheckingResult对象数组,如果没有匹配,将有一个带有range {NSNotFound, 0}的NSTextCheckingResult对象。
这是遗产。目标-C没有选项词的概念。
为什么不为NSRegularExpression创建自己的扩展,它提供了一个返回可选方法的方法,如果没有匹配,则为零?
https://stackoverflow.com/questions/29449322
复制相似问题