Skip to content

swift-foundations/swift-url-form-coding

Repository files navigation

swift-url-form-coding

CI Development Status

A Swift package for encoding and decoding application/x-www-form-urlencoded data with Codable support.

Overview

swift-url-form-coding provides type-safe conversion between Swift's Codable types and URL-encoded form data, the standard format used by HTML forms and many web APIs.

Features

  • Codable Integration: Seamlessly encode/decode Swift types to/from form data
  • Multiple Encoding Strategies: Support for PHP-style brackets, indexed arrays, and more
  • RFC Compliant: Built on RFC 2388 and WHATWG URL Encoding
  • Swift 6.0: Full strict concurrency support
  • Comprehensive Tests: 158+ tests covering edge cases and round-trip conversions

Installation

Add this package to your Package.swift:

dependencies: [
    .package(url: "https://github.com/coenttb/swift-url-form-coding", from: "0.1.0")
]

Then add the product to your target:

.target(
    name: "YourTarget",
    dependencies: [
        .product(name: "URLFormCoding", package: "swift-url-form-coding")
    ]
)

Supported Platforms

  • macOS 14.0+
  • iOS 17.0+
  • tvOS 17.0+
  • watchOS 10.0+
  • Swift 6.1+

Quick Start

Basic Encoding/Decoding

import URLFormCoding

struct User: Codable {
    let name: String
    let email: String
    let age: Int
}

// Encoding
let encoder = Form.Encoder()
let user = User(name: "John Doe", email: "john@example.com", age: 30)
let formData = try encoder.encode(user)
// Result: "name=John%20Doe&email=john%40example.com&age=30"

// Decoding
let decoder = Form.Decoder()
let decodedUser = try decoder.decode(User.self, from: formData)

Array Encoding Strategies

struct SearchQuery: Codable {
    let tags: [String]
}

let query = SearchQuery(tags: ["swift", "ios", "server"])

// Accumulate Values (default)
let encoder1 = Form.Encoder()
encoder1.arrayEncodingStrategy = .accumulateValues
// Result: "tags=swift&tags=ios&tags=server"

// Brackets (PHP/Rails style)
let encoder2 = Form.Encoder()
encoder2.arrayEncodingStrategy = .brackets
// Result: "tags[]=swift&tags[]=ios&tags[]=server"

// Indexed Brackets
let encoder3 = Form.Encoder()
encoder3.arrayEncodingStrategy = .bracketsWithIndices
// Result: "tags[0]=swift&tags[1]=ios&tags[2]=server"

Dependencies

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Related Packages

Credits

Originally based on PointFree's UrlFormEncoding from swift-web, modernized with RFC compliance.

About

A Swift package for type-safe URL-encoded form data encoding and decoding.

Topics

Resources

License

Code of conduct

Contributing

Stars

1 star

Watchers

0 watching

Forks

Sponsor this project

 

Contributors

Languages