简体   繁体   中英

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

  • Annotated type of the regex in this way:
let regex: Regex<(Substring, Substring, Substring, Date, Date, Int)> = Regex { ... }
  • Make explicit the type of transform closure in the two TryCapture
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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