### Project Setup and Basic Commands (Bash) Source: https://github.com/toon-format/toon-swift/blob/main/CONTRIBUTING.md This section details the initial steps for setting up the toon-swift project, including cloning the repository, building the project, and running tests. It also provides an optional command for generating an Xcode project. ```bash git clone https://github.com/toon-format/toon-swift.git cd toon-swift swift build swift test swift package generate-xcodeproj ``` -------------------------------- ### Swift Package Manager Installation Source: https://github.com/toon-format/toon-swift/blob/main/README.md Provides instructions for adding the `toon-swift` library to a Swift project using the Swift Package Manager. It includes the necessary lines to add to the `Package.swift` file and how to link the dependency to a target. ```swift dependencies: [ .package(url: "https://github.com/toon-format/toon-swift.git", from: "0.3.0") ] // Then add the dependency to your target: .target(name: "YourTarget", dependencies: ["ToonFormat"]) ``` -------------------------------- ### Getting TOON Specification Version in Swift Source: https://github.com/toon-format/toon-swift/blob/main/README.md Provides an example of how to retrieve the supported TOON specification version string from the library. ```swift print(toonSpecVersion) // "3.0" ``` -------------------------------- ### Customize TOON Delimiters for Encoding Source: https://github.com/toon-format/toon-swift/blob/main/README.md Illustrates how to configure `TOONEncoder` to use alternative delimiters like tab or pipe instead of the default comma. This can further reduce token usage. The example encodes an array of custom `Item` structs. ```swift import ToonFormat struct Item: Codable { let sku: String let name: String let qty: Int let price: Double } let items = [ Item(sku: "A1", name: "Widget", qty: 2, price: 9.99), Item(sku: "B2", name: "Gadget", qty: 1, price: 14.5) ] let encoder = TOONEncoder() encoder.delimiter = .tab // or .pipe let data = try encoder.encode(["items": items]) // Output with tab delimiter: // items[2 ]{sku name qty price}: // A1 Widget 2 9.99 // B2 Gadget 1 14.5 // Output with pipe delimiter: // items[2|]{sku|name|qty|price}: // A1|Widget|2|9.99 // B2|Gadget|1|14.5 ``` -------------------------------- ### Running Tests (Bash) Source: https://github.com/toon-format/toon-swift/blob/main/CONTRIBUTING.md This section explains how to execute the test suite for the toon-swift project. It includes commands for running tests with standard output and with verbose output for detailed logging. ```bash swift test swift test -v ``` -------------------------------- ### Code Formatting (Bash) Source: https://github.com/toon-format/toon-swift/blob/main/CONTRIBUTING.md This command demonstrates how to format the Swift code within the project using the `swift-format` tool. It recursively formats files in the Sources and Tests directories. ```bash swift-format format --in-place --recursive Sources/ Tests/ ``` -------------------------------- ### Common Swift Package Manager Build Tasks (Bash) Source: https://github.com/toon-format/toon-swift/blob/main/CONTRIBUTING.md This provides a consolidated list of essential Swift Package Manager commands for daily development. It covers building, testing (with and without verbose output), cleaning build artifacts, and generating an Xcode project. ```bash swift build swift test swift test -v swift package clean swift package generate-xcodeproj ``` -------------------------------- ### TOONDecoder - Basic Decoding in Swift Source: https://context7.com/toon-format/toon-swift/llms.txt Illustrates basic decoding of TOON format data back into Swift Codable types using TOONDecoder. It shows how to decode a simple object with various data types. ```swift import ToonFormat struct User: Codable { let id: Int let name: String let email: String let active: Bool } let toonString = """ id: 42 name: Alice Smith email: alice@example.com active: true """ do { let decoder = TOONDecoder() let data = toonString.data(using: .utf8)! let user = try decoder.decode(User.self, from: data) print("Decoded user: \(user.name), ID: \(user.id)") // Output: Decoded user: Alice Smith, ID: 42 } catch { print("Decoding failed: \(error)") } ``` -------------------------------- ### Configuring Decoding Limits in Swift Source: https://github.com/toon-format/toon-swift/blob/main/README.md Demonstrates how to set decoding limits on a TOONDecoder to protect against malicious or malformed input. These limits control maximum input size, nesting depth, and the number of keys/array elements. ```swift let decoder = TOONDecoder() decoder.limits = TOONDecoder.DecodingLimits( maxInputSize: 1024 * 1024, // 1 MB maxDepth: 64, maxObjectKeys: 1000, maxArrayLength: 10000 ) ``` -------------------------------- ### Basic Encoding with TOONEncoder in Swift Source: https://context7.com/toon-format/toon-swift/llms.txt Demonstrates basic encoding of a Swift Codable struct into TOON format using TOONEncoder. This function takes a Codable object and returns TOON formatted data. Dependencies include the ToonFormat library. ```swift import ToonFormat struct User: Codable { let id: Int let name: String let email: String let active: Bool } let user = User( id: 42, name: "Alice Smith", email: "alice@example.com", active: true ) do { let encoder = TOONEncoder() let data = try encoder.encode(user) let output = String(data: data, encoding: .utf8)! print(output) // Output: // id: 42 // name: Alice Smith // email: alice@example.com // active: true } catch { print("Encoding failed: \(error)") } ``` -------------------------------- ### Encoding with Key Folding in Swift Source: https://github.com/toon-format/toon-swift/blob/main/README.md Shows how to use key folding with TOONEncoder to flatten nested objects into dotted paths, reducing token count and indentation. This is useful for simplifying complex data structures. ```swift struct Config: Codable { struct Database: Codable { struct Connection: Codable { let host: String let port: Int } let connection: Connection } let database: Database } let config = Config( database: .init( connection: .init(host: "localhost", port: 5432) ) ) let encoder = TOONEncoder() encoder.keyFolding = .safe let data = try encoder.encode(config) ``` -------------------------------- ### TOONDecoder - Path Expansion in Swift Source: https://context7.com/toon-format/toon-swift/llms.txt Shows how TOONDecoder automatically expands dotted keys into nested object structures. The `expandPaths` property is demonstrated to enable this feature. ```swift import ToonFormat struct Config: Codable { struct Database: Codable { struct Connection: Codable { let host: String let port: Int } let connection: Connection } let database: Database } let toonString = """ database.connection: host: localhost port: 5432 """ do { let decoder = TOONDecoder() decoder.expandPaths = .automatic // Default setting let data = toonString.data(using: .utf8)! let config = try decoder.decode(Config.self, from: data) print("Host: \(config.database.connection.host)") print("Port: \(config.database.connection.port)") // Output: // Host: localhost // Port: 5432 } catch { print("Decoding failed: \(error)") } ``` -------------------------------- ### Encode and Decode Swift Struct with TOON Source: https://github.com/toon-format/toon-swift/blob/main/README.md Demonstrates basic encoding of a Swift struct to TOON format and decoding it back. This process uses the `TOONEncoder` and `TOONDecoder` from the `ToonFormat` library. It requires the struct to conform to the `Codable` protocol. The output is a string representation of the TOON data. ```swift import ToonFormat struct User: Codable { let id: Int let name: String let tags: [String] let active: Bool } // Encoding let user = User( id: 123, name: "Ada", tags: ["reading", "gaming"], active: true ) let encoder = TOONEncoder() let data = try encoder.encode(user) print(String(data: data, encoding: .utf8)!) // id: 123 // name: Ada // tags[2]: reading,gaming // active: true // Decoding let decoder = TOONDecoder() let decoded = try decoder.decode(User.self, from: data) print(decoded.name) // "Ada" ``` -------------------------------- ### Special Type Handling: Date, URL, Data Encoding/Decoding (Swift) Source: https://context7.com/toon-format/toon-swift/llms.txt Illustrates the serialization and deserialization of special Foundation types including Date, URL, and Data using TOONEncoder and TOONDecoder in Swift. Dates are encoded in ISO 8601 format, URLs as strings, and Data as Base64. ```swift import ToonFormat import Foundation struct Record: Codable { let timestamp: Date let website: URL let attachment: Data } let record = Record( timestamp: Date(timeIntervalSince1970: 1640000000), website: URL(string: "https://example.com")!, attachment: Data([0x48, 0x65, 0x6C, 0x6C, 0x6F]) ) do { // Encoding let encoder = TOONEncoder() let encoded = try encoder.encode(record) print("Encoded:") print(String(data: encoded, encoding: .utf8)!) // Output: // timestamp: 2021-12-20T11:06:40.000Z // website: https://example.com // attachment: SGVsbG8= // Decoding let decoder = TOONDecoder() let decoded = try decoder.decode(Record.self, from: encoded) print("\nDecoded timestamp: \(decoded.timestamp)") print("Decoded website: \(decoded.website)") print("Decoded data bytes: \(decoded.attachment.count)") } catch { print("Error: \(error)") } ``` -------------------------------- ### Querying TOON Specification Version (Swift) Source: https://context7.com/toon-format/toon-swift/llms.txt Provides a simple code snippet in Swift to check the supported TOON specification version by accessing the `toonSpecVersion` constant from the ToonFormat library. ```swift import ToonFormat // Query the specification version print("TOON Spec Version: \(toonSpecVersion)") // Output: TOON Spec Version: 3.0 ``` -------------------------------- ### Encoding Tabular Arrays in Swift Source: https://github.com/toon-format/toon-swift/blob/main/README.md Demonstrates encoding an array of structs with primitive fields into an efficient tabular format using TOONEncoder. This is suitable for objects with identical primitive fields. ```swift struct Item: Codable { let sku: String let qty: Int let price: Double } let items = [ Item(sku: "A1", qty: 2, price: 9.99), Item(sku: "B2", qty: 1, price: 14.5) ] let encoder = TOONEncoder() let data = try encoder.encode(["items": items]) ``` -------------------------------- ### TOONDecoder Error Handling with Detailed Information (Swift) Source: https://context7.com/toon-format/toon-swift/llms.txt Demonstrates comprehensive error handling for TOON decoding using Swift. Catches specific TOONDecodingError types like typeMismatch, invalidFormat, and countMismatch, providing detailed information including line numbers for debugging. ```swift import ToonFormat struct User: Codable { let id: Int let name: String } let invalidTOON = """ id: not_a_number name: Alice """ do { let decoder = TOONDecoder() let data = invalidTOON.data(using: .utf8)! let user = try decoder.decode(User.self, from: data) print("User: \(user)") } catch TOONDecodingError.typeMismatch(let expected, let actual) { print("Type mismatch: expected \(expected), got \(actual)") // Output: Type mismatch: expected int, got string } catch TOONDecodingError.invalidFormat(let message) { print("Invalid format: \(message)") } catch TOONDecodingError.countMismatch(let expected, let actual, let line) { print("Count mismatch at line \(line): expected \(expected), got \(actual)") } catch { print("Decoding failed: \(error)") } ``` -------------------------------- ### TOONEncoder - Flatten Depth Control in Swift Source: https://context7.com/toon-format/toon-swift/llms.txt Demonstrates how to control the maximum depth of key folding for nested structures using TOONEncoder. It shows how to configure `flattenDepth` to limit the nesting level during encoding. ```swift import ToonFormat struct DeepConfig: Codable { struct Level1: Codable { struct Level2: Codable { struct Level3: Codable { struct Level4: Codable { let value: String } let level4: Level4 } let level3: Level3 } let level2: Level2 } let level1: Level1 } let deepConfig = DeepConfig( level1: .init( level2: .init( level3: .init( level4: .init(value: "deep value") ) ) ) ) do { let encoder = TOONEncoder() encoder.keyFolding = .safe encoder.flattenDepth = 2 // Only fold up to 2 levels let data = try encoder.encode(deepConfig) print(String(data: data, encoding: .utf8)!) // Output: // level1.level2: // level3: // level4: // value: deep value } catch { print("Encoding failed: \(error)") } ``` -------------------------------- ### TOONEncoder Inline Primitive Arrays Encoding (Swift) Source: https://context7.com/toon-format/toon-swift/llms.txt Shows how to encode arrays of primitive types (String, Int, Bool) into a compact, inline format using TOONEncoder in Swift. The output demonstrates the compressed representation of array elements. ```swift import ToonFormat struct Data: Codable { let tags: [String] let scores: [Int] let flags: [Bool] } let data = Data( tags: ["swift", "ios", "mobile"], scores: [85, 92, 78, 95], flags: [true, false, true] ) do { let encoder = TOONEncoder() let encoded = try encoder.encode(data) print(String(data: encoded, encoding: .utf8)!) // Output: // tags[3]: swift,ios,mobile // scores[4]: 85,92,78,95 // flags[3]: true,false,true } catch { print("Encoding failed: \(error)") } ``` -------------------------------- ### TOONDecoder - Tabular Array Decoding in Swift Source: https://context7.com/toon-format/toon-swift/llms.txt Demonstrates decoding tabular format arrays into Swift arrays of objects using TOONDecoder. This is useful for parsing data where each line represents an item in an array. ```swift import ToonFormat struct Product: Codable { let sku: String let name: String let quantity: Int let price: Double } let toonString = """ products[3]{sku,name,quantity,price}: A1,Widget,10,9.99 B2,Gadget,5,14.5 C3,Sprocket,20,7.25 """ do { let decoder = TOONDecoder() let data = toonString.data(using: .utf8)! let result = try decoder.decode([String: [Product]].self, from: data) if let products = result["products"] { for product in products { print("\(product.sku): \(product.name) - $\(product.price)") } } // Output: // A1: Widget - $9.99 // B2: Gadget - $14.5 // C3: Sprocket - $7.25 } catch { print("Decoding failed: \(error)") } ``` -------------------------------- ### Custom Delimiter Encoding with TOONEncoder in Swift Source: https://context7.com/toon-format/toon-swift/llms.txt Shows how to configure TOONEncoder to use custom delimiters like pipe (|) or tab for increased token savings in TOON format serialization. This allows flexibility in data representation. The ToonFormat library is a prerequisite. ```swift import ToonFormat struct Item: Codable { let id: Int let category: String let inStock: Bool } let items = [ Item(id: 1, category: "Electronics", inStock: true), Item(id: 2, category: "Books", inStock: false) ] do { // Using pipe delimiter let pipeEncoder = TOONEncoder() pipeEncoder.delimiter = .pipe let pipeData = try pipeEncoder.encode(["items": items]) print(String(data: pipeData, encoding: .utf8)!) // Output: // items[2|]{id|category|inStock}: // 1|Electronics|true // 2|Books|false // Using tab delimiter let tabEncoder = TOONEncoder() tabEncoder.delimiter = .tab let tabData = try tabEncoder.encode(["items": items]) print(String(data: tabData, encoding: .utf8)!) // Output with tabs between values } catch { print("Encoding failed: \(error)") } ``` -------------------------------- ### Encoding Arrays of Arrays in Swift Source: https://github.com/toon-format/toon-swift/blob/main/README.md Illustrates how to encode arrays containing primitive inner arrays using TOONEncoder. This method is used for nested arrays of simple data types. ```swift let pairs = [[1, 2], [3, 4]] let encoder = TOONEncoder() let data = try encoder.encode(["pairs": pairs]) ``` -------------------------------- ### Tabular Array Encoding with TOONEncoder in Swift Source: https://context7.com/toon-format/toon-swift/llms.txt Encodes an array of uniform Swift Codable objects into a compact tabular TOON format, including headers for efficiency. This method is ideal for representing lists of similar data structures. Requires the ToonFormat library. ```swift import ToonFormat struct Product: Codable { let sku: String let name: String let quantity: Int let price: Double } let products = [ Product(sku: "A1", name: "Widget", quantity: 10, price: 9.99), Product(sku: "B2", name: "Gadget", quantity: 5, price: 14.50), Product(sku: "C3", name: "Sprocket", quantity: 20, price: 7.25) ] do { let encoder = TOONEncoder() let data = try encoder.encode(["products": products]) print(String(data: data, encoding: .utf8)!) // Output: // products[3]{sku,name,quantity,price}: // A1,Widget,10,9.99 // B2,Gadget,5,14.5 // C3,Sprocket,20,7.25 } catch { print("Encoding failed: \(error)") } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.