Search code examples
swiftregexxcodestatic-analysisswiftlint

What is the easiest way to systematically replace ".doOnComplete {}" with ".do(onComplete: {})" in a large Swift codebase?


What is the best way to replace:

.doOnComplete {
    // Implementation
}

with

.do(
    onComplete: {
        // Implementation
    }
)

throughout a large Swift codebase? Given that there are a large number of these manually replacing is not an option.


Solution

  • Depending on the complexity of your code, this could be very hard to achieve.

    It the correct approach is indeed to try to capture the implementation block. However, it is important to look out for balanced curly braces, e.g. like this:

    \.doOnComplete\s*(\{(?>[^{}]+|(?1))*\})
    

    and then replace with

    .do(\n\tonComplete: $1\t\n)
    

    Demo

    PS: I tried to pretty print the code but you will have to reformat the code anyways.