gpt4 book ai didi

regex - NSRegularExpression 可选返回

转载 作者:行者123 更新时间:2023-11-28 13:14:48 25 4
gpt4 key购买 nike

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

每次我使用这个类时,我都必须检查返回的 [AnyObject] 数组,看看它的计数是否 > 0,然后再使用它。相反,如果没有返回任何内容,则能够使用 Optional 绑定(bind)或检查 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 是一个早在 Swift 出现之前就已经存在的类。 matchesInString:options:range: 的约定声明它返回一个 NSTextCheckingResult 对象数组,如果没有匹配项,将有一个 NSTextCheckingResult 范围为 {NSNotFound, 0} 的对象。

这是一个遗留的东西。 Objective-C 没有可选的概念。

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

关于regex - NSRegularExpression 可选返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com