gpt4 book ai didi

swift - 从 compactMap 返回和退出

转载 作者:行者123 更新时间:2023-11-28 11:37:30 28 4
gpt4 key购买 nike

我正在使用正则表达式规则检查一些动态文本,对正则表达式模式数组的每个索引使用switch .一切正常,但在最后一个 case 中,我希望 map 停止映射并尽早返回!但似乎我无法在 map 函数中 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 [:]
}

最佳答案

如果你不使用results,你就不需要使用compactMap。而且没有办法退出compactMap。在循环中使用。

关于swift - 从 compactMap 返回和退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54668060/

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