2015-04-04 74 views
0

我一直在使用NSRegularExpression相當多,我一直在想,它沒有任何意義,方法matchesInString() 不返回一個可選的數組。NSRegularExpression可選返回

每次我使用這個類時,我都必須檢查返回的[AnyObject]數組,看看在我使用它之前count是否大於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

NSRegularExpression是一個很久以前就存在的類。 matchesInString:options:range:的合同規定它返回一個NSTextCheckingResult對象數組,如果沒有任何匹配項,則會有一個NSTextCheckingResult對象,其範圍爲{NSNotFound, 0}

這是一件遺留的事情。 Objective-C沒有可選的概念。

爲什麼不創建自己的NSRegularExpression擴展提供了一個返回可選的方法,如果沒有匹配則返回nil?

+0

好主意我的男人。 – Woodstock 2015-04-04 18:04:38