0

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.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Nil
  • 11
  • 4

1 Answers1

0

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.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • I thought the detail of `DateFormatter` initialization wasn't important, so I left that out. I shouldn't have do that. Sorry. – Nil Jul 16 '22 at 01:07
  • I moved the `DateFormatter` declaration out of the Regex builder as you advised, and it worked! Thank you for the solution! – Nil Jul 16 '22 at 01:11