我正在使用 Regex规则检查一些动态文本,对每个switch
的正则表达式模式index
使用array
。一切正常,但在最后一个case
中,我希望地图停止映射并尽早返回!但似乎我无法在地图函数中return
!还有更好的方法或解决方案吗?
fileprivate func regexMatch(pattern regex: [String], in text: String) -> Dictionary<String, Any>
{
do
{
for (index, string) in regex.enumerated()
{
let regex = try NSRegularExpression(pattern: string, options: .caseInsensitive)
let results: [NSTextCheckingResult] = regex.matches(in: text, range: NSRange(text.startIndex..., in: text))
_ = results.compactMap
{
/* If i put a guard check to see if result is filled
* then return, works fine but iterates again for the next index and keeps returning till it’s over!
*/
switch index
{
case 0:
// Does something
case 1:
// Does something else
case 2:
// Does the last thing
// If succeed finding the match! Just return or exit the map!
let carNames = String(Range($0.range, in: text).map { String(text[$0]) }!).lowercased()
for case let car as Car in carsList!
{
if spottedCarNamesInReceipt.contains(car.name!.lowercased())
{
result["car"] = car
return // This does work though, but the map starts iterating again over the next index!
}
}
default:
break;
}
}
}
return result
} catch let error
{
print("Invalid regex: \(error.localizedDescription)")
return [:]
}
答案 0 :(得分:1)
如果不使用结果,则无需使用compactMap。而且没有办法退出compactMap。用于周期内。
答案 1 :(得分:1)
使用return
语句forEach
循环或任何类型的Maps
,仅针对闭包中的当前调用退出,而for...in
循环也退出所有后续的后续调用。因此for...in
解决了需要提前退出的问题。