swift-parsing icon indicating copy to clipboard operation
swift-parsing copied to clipboard

Dedicated Module and Improvements to Conversions

Open woodymelling opened this issue 1 year ago • 0 comments

I’ve been exploring the concept of Conversions recently and discovered they’re incredibly powerful. They seem to be a bit more broad than the ParserPrinters provided by swift-parsing.

A ParserPrinter transforms nebulous data into structured data while consuming part of the input, and can also print the structured data back into a the nebulous form. In contrast, a Conversion focuses solely on the ability to convert between two types, potentially throwing errors, without any notion of input consumption or output printing. This aligns with the “parse, don’t validate” philosophy, making Conversions useful when dealing with data that isn’t strictly string-based—allowing you to transform it directly into Swift types without worrying about parsing steps.

I’m submitting this PR as a result of these explorations and am curious if this approach is of interest. I believe it could be broadly applicable, especially when defining persistence strategies.

This PR includes:

  • Extracting Conversions into their own module, emphasizing their utility even outside of parsing scenarios.
  • Introducing a ResultBuilder for constructing complex conversions from simpler ones. For example:
struct PostConversion: Conversion {
    typealias Input = [FileContent<Data>]
    typealias Output = [Blog.Post]

    var body: some Conversion<Input, Output> {
        Conversions.MapValues {
            FileContentConversion(.json(Blog.PostBody.self))

            AnyConversion {
                Blog.Post(
                    slug: $0.fileName,
                    body: $0.content
                )
            } unapply: {
                FileContent(
                    fileName: $0.slug,
                    data: $0.body
                )
            }
        }
    }
}
  • Providing a set of useful conversions, such as inversion of existing conversions, value mapping, and dictionary transformations.

woodymelling avatar Dec 06 '24 07:12 woodymelling