Object Parsing: turn natural language strings into Swift objects, declaratively

I made a package that defines a @ParsableObject macro to let you parse strings into Swift objects declaratively:

import ObjectParsing

@ParsableObject
struct SalesRecord {
    let quantity: Int
    let date: Date
}

let record: SalesRecord = try "We sold 130 copies yesterday".parseObject()

Properties are matched in declaration order (pass ordering: .unordered to match in any order).

You can nest parsable objects too:

@ParsableObject
struct Person {
    let age: Int
    let height: Double
    let bankBalance: Decimal
    let pace: Pace
}

@ParsableObject
struct Pace {
    let distanceTravelled: Distance
    let timeTaken: Time
}

let person: Person = try "I am 37 years old, 176 cm tall and have $2,500 in my bank account. I ran 650 metres, which took me 3 minutes 30 seconds".parseObject()
// Person(age: 37, height: 176.0, bankBalance: 2500, pace: Pace(distanceTravelled: 650.0 m, timeTaken: 3.5 min))

Inspiration

This API was inspired by the FoundationModels @Generable macro & Swift Codable.

Unlike @Generable, @ParsableObject involves no LLM calls: it's deterministic, runs locally, and is fast enough to call on every keystroke (tens to low-hundreds of microseconds per parse).

Supported data types

You can use all the standard Foundation data types in your model objects (numbers, dates, Foundation measurements, date intervals) β€” basically anything that can be expressed as a string.

There's also support for higher-order primitives like places, flights, currencies, time codes, IP addresses, and tags, and you can extend the parser with your own types by pre-declaring the strings you want to match in a String enum. See the repo for details.

Compared to regex

Object parsing uses a different approach to parsing from regular expressions. Rather than describing how data is formatted, you only declare what data types you want to extract, and in what order.

If you do need format-based extraction, regex is still the right tool.

Open-source & dependencies

This package is open source but it depends on SoulverCore for the actual parsing β€” a closed-source framework distributed as an xcframework on Apple platforms, and as a dynamic library on Linux & Windows. SoulverCore is free for personal / non-commercial use. A license is required for commercial use.

3 Likes

Cool - good job! Although I wonder how useful it is given that on your examples all fields are non-optional (eg Person). If you require all data, why not use something structured like JSON? This feels useful when trying to parse out as much as possible from natural language with optional fields.

An example why it is useful with all fields non-optional but not using structured data like JSON would be good :)