[英]Swift 5.7 - The compiler cannot type-check complex regex which contains 5 captures
我寫了這段代碼:
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
}
並發生錯誤:
編譯器無法在合理的時間內對該表達式進行類型檢查; 嘗試將表達式分解為不同的子表達式
我應該如何解決這個錯誤?
我試過的
let regex: Regex<(Substring, Substring, Substring, Date, Date, Int)> = Regex { ... }
TryCapture
中明確transform
閉包的類型TryCapture { OneOrMore(.any) } transform: { (createdDateString: Substring) -> Date in
dateFormatter.date(from: String(createdDateString))
}
兩者都沒有解決錯誤。
您有一個日期格式化程序,但您根本沒有配置它,那么它應該格式化什么? 設置日期格式使代碼為我編譯。
例子
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
請注意,我將 DateFormatter 聲明移出 Regex 構建器,因為將其放入內部會使編譯器不滿意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.