Home > Software design >  Swift 5.7 - The compiler cannot type-check complex regex which contains 5 captures
Swift 5.7 - The compiler cannot type-check complex regex which contains 5 captures

Time:07-16

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.

CodePudding user response:

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.

  • Related