[英]Swift 5.7 - The compiler cannot type-check complex regex which contains 5 captures
I wrote this code:我写了这段代码:
let regex = Regex {
let newline = #/\r|\n|\r\n/#
let doubleNewline = Repeat(newline, count: 2)
let dateFormatter = DateFormatter()
"# Title"
newline
Capture { ZeroOrMore(.any) }
doubleNewline
"# Subtitle"
newline
Capture { ZeroOrMore(.any) }
doubleNewline
"# Created at"
newline
TryCapture { OneOrMore(.any) } transform: { createdDateString in
dateFormatter.date(from: String(createdDateString))
}
doubleNewline
"# Exported at"
newline
TryCapture { OneOrMore(.any) } transform: { exportedDateString in
dateFormatter.date(from: String(exportedDateString))
}
doubleNewline
"# Article count"
newline
Capture {
.localizedInteger
}
doubleNewline
"# Articles"
newline
ZeroOrMore {
#/[\s\S]/#
}
newline
}
and the error occurs:并发生错误:
The compiler is unable to type-check this expression in reasonable time;编译器无法在合理的时间内对该表达式进行类型检查; try breaking up the expression into distinct sub-expressions尝试将表达式分解为不同的子表达式
How should I fix this error?我应该如何解决这个错误?
What I tried我试过的
let regex: Regex<(Substring, Substring, Substring, Date, Date, Int)> = Regex { ... }
transform
closure in the two TryCapture
在两个TryCapture
中明确transform
闭包的类型TryCapture { OneOrMore(.any) } transform: { (createdDateString: Substring) -> Date in
dateFormatter.date(from: String(createdDateString))
}
Neither resolved the error.两者都没有解决错误。
You have a date formatter but you haven't configured it at all so what is it supposed to format?您有一个日期格式化程序,但您根本没有配置它,那么它应该格式化什么? Setting a date format made the code compile for me.设置日期格式使代码为我编译。
Example例子
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
Note that I moved the DateFormatter declaration out of the Regex builder since having it inside made the compiler unhappy.请注意,我将 DateFormatter 声明移出 Regex 构建器,因为将其放入内部会使编译器不满意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.