繁体   English   中英

Swift 5.7 - 编译器无法对包含 5 个捕获的复杂正则表达式进行类型检查

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM