### Example: converting TOMLArray to [Any] Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLArray.md Shows how to convert a TOMLArray to a Swift array using the Array initializer. ```swift let swiftArray: [Any] = try Array(tomlArray) ``` -------------------------------- ### Example: Parsing TOML from Data and String with error handling Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Shows how to create a TOMLTable from Data read from a file, from a multi-line string, and how to catch TOMLError for parsing failures. The example includes an unterminated array that triggers a syntax error. ```swift import Foundation let data = try Data(contentsOf: URL(fileURLWithPath: "config.toml")) let table = try TOMLTable(source: data) // String path let document = """ owner = "dduan" [server] host = "127.0.0.1" """ let root = try TOMLTable(source: document) // Error handling: parsing failures are always TOMLError at this layer. do { _ = try TOMLTable(source: "key = [1, 2,") // unterminated array } catch let error as TOMLError { print(error.description) // "(Line 1) Syntax error: ..." } ``` -------------------------------- ### Example: decoding a TOMLArray with Codable Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLArray.md Shows how to decode a TOMLArray using TOMLDecoder with a Codable struct. ```swift struct Config: Codable { let servers: TOMLArray // works with TOMLDecoder } let config = try TOMLDecoder().decode(Config.self, from: tomlString) ``` -------------------------------- ### Full configuration example for TOMLDecoder Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/configuration.md Complete configuration with strict type matching, snake case conversion, proleptic Gregorian calendar for pre-1582 dates, and Apple reference date for time intervals. ```swift // Full configuration example let decoder = TOMLDecoder( isLenient: false, // strict type matching strategy: .init( key: .convertFromSnakeCase, // first_name -> firstName date: .prolepticGregorianCalendar, // correct for pre-1582 dates timeInterval: .since2001 // Apple reference date ) ) ``` -------------------------------- ### TOMLTable usage example Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Shows how to use TOMLTable to access various value types, including the `exactMatch` parameter and error handling for type mismatches. ```swift let toml = """ release = 2024-01-02T03:04:05Z date_only = 2024-01-02 tags = ["a", "b"] limits = { max = 10 } """ let root = try TOMLTable(source: toml) let release = try root.offsetDateTime(forKey: "release") let dateOnly = try root.localDate(forKey: "date_only") // exactMatch: false lets a "fuller" value satisfy a simpler request: let sameDate = try root.localDate(forKey: "release", exactMatch: false) let tags = try root.array(forKey: "tags") let firstTag = try tags.string(atIndex: 0) let limits = try root.table(forKey: "limits") let maxValue = try limits.integer(forKey: "max") do { _ = try root.string(forKey: "release") // release is a date-time, not a string } catch let error as TOMLError { print(error.description) // "(Line 1) Type mismatch at table key 'release': expected string." } ``` -------------------------------- ### LocalDate Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/DateTimeTypes.md Documentation for the LocalDate struct, including its initializers, computed properties, and usage examples. ```APIDOC ## LocalDate ### Description A local date type with year, month, and day components. Provides validating and non-validating initializers, plus computed properties for validation and string description. ### Initializers ```swift public init(validatingYear year: UInt16, month: UInt8, day: UInt8) throws(TOMLError) public init(year: UInt16, month: UInt8, day: UInt8) ``` ### Parameters - **year** (UInt16) - Required - Year component, valid range [1, 9999] - **month** (UInt8) - Required - Month component, valid range [1, 12] - **day** (UInt8) - Required - Day component, valid range depends on month/year ### Throws - `TOMLError` (`.invalidDateTimeComponents`) when `isValid` is `false` (validating initializer only) ### Computed Properties ```swift public var isValid: Bool public var description: String // "YYYY-MM-DD" zero-padded ``` ### Usage Example ```swift let validated = try LocalDate(validatingYear: 2024, month: 2, day: 29) // leap year, OK do { _ = try LocalDate(validatingYear: 2024, month: 2, day: 30) } catch let error as TOMLError { print(error.description) // "Invalid date-time components: Invalid local date components: 2024-02-30" } ``` ``` -------------------------------- ### LocalDate Usage and Validation Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/DateTimeTypes.md Examples of parsing TOML date types and using the validating initializer for LocalDate. ```swift let toml = """ local_dt = 1979-05-27T07:32:00 local_d = 1979-05-27 local_t = 07:32:00.999 """ let root = try TOMLTable(source: toml) let dt = try root.localDateTime(forKey: "local_dt") let d = try root.localDate(forKey: "local_d") let t = try root.localTime(forKey: "local_t") // exactMatch: false — a fuller value satisfies a simpler request let dateOnly = try root.localDate(forKey: "local_dt", exactMatch: false) let timeOnly = try root.localTime(forKey: "local_dt", exactMatch: false) print(t.nanosecond) // 999_000_000 print(t.description) // "07:32:00.999" (trailing zeros of the fraction trimmed) // Validating initializers let validated = try LocalDate(validatingYear: 2024, month: 2, day: 29) // leap year, OK do { _ = try LocalDate(validatingYear: 2024, month: 2, day: 30) } catch let error as TOMLError { print(error.description) // "Invalid date-time components: Invalid local date components: 2024-02-30" } ``` -------------------------------- ### Example: accessing TOMLArray elements Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLArray.md Shows how to parse a TOML array and access its elements by type, including error handling for type mismatches and out-of-bounds access. ```swift let toml = """ list = [ "apple", "banana", { brand = "Tart", size = 3 }, [1, 2, 3], ] """ let root = try TOMLTable(source: toml) let list = try root.array(forKey: "list") let fruit = try list.string(atIndex: 0) let nested = try list.table(atIndex: 2) let nestedInt = try nested.integer(forKey: "size") let deep = try list.array(atIndex: 3) let deepInt = try deep.integer(atIndex: 1) // 2 // Error handling: out-of-bounds and type errors are TOMLError. do { _ = try list.integer(atIndex: 0) // element 0 is a String } catch let error as TOMLError { print(error.description) // "(Line 2) Type mismatch at array index 0: expected integer." } print(list.count) // 4 ``` -------------------------------- ### description property and usage Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/OffsetDateTime.md Provides the string representation of the OffsetDateTime. The example demonstrates parsing a TOML string and accessing its components. ```swift public var description: String ``` ```swift let toml = "release = 1979-05-27T07:32:00-07:00" let table = try TOMLTable(source: toml) let release = try table.offsetDateTime(forKey: "release") print(release.date.year) // 1979 print(release.time.minute) // 32 print(release.offset) // -420 print(release.description) // "1979-05-27T07:32:00-07:00" print(release.timeIntervalSince1970) // 296_663_520.0 (proleptic Gregorian) ``` -------------------------------- ### Converting TOMLTable to Dictionary Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Usage example for converting a TOMLTable instance into a Swift dictionary. This process validates fields recursively and may be slow for large documents. ```swift let dict: [String: Any] = try Dictionary(tomlTable) ``` -------------------------------- ### Custom key mapping with uppercase transformation Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/Strategies.md Shows decoding with a custom strategy that uppercases all keys, useful for a legacy property naming scheme. The property name must match the transformed TOML key. The example decodes the TOML string "server = \"prod\"". ```swift // Custom mapping: uppercase all keys for a legacy property naming scheme. let decoder = TOMLDecoder(strategy: .init(key: .custom { $0.uppercased() })) struct Config: Codable { let SERVER: String // matches TOML key "server" } let config = try decoder.decode(Config.self, from: "server = \"prod\"") ``` -------------------------------- ### Dictionary.init(_ tomlTable:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/index.md Converts a TOMLTable to a Swift dictionary. ```APIDOC ## Dictionary.init(_ tomlTable:) ### Description An extension initializer that creates a `[String: Any]` dictionary from a `TOMLTable`. ### Usage ```swift let dict = Dictionary(tomlTable) ``` ``` -------------------------------- ### init(source:) (String) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Creates a root-level TOMLTable by parsing a TOML document from a String. Throws TOMLError if the document is invalid. ```APIDOC ## init(source:) (String) ### Description Creates a root-level TOMLTable by parsing a TOML document from a String. Throws TOMLError if the document is invalid. ### Method Initializer ### Signature ```swift public init(source: String) throws(TOMLError) ``` ### Parameters - **source** (String) - Required - The TOML document to parse ### Throws TOMLError if the document is invalid (parse-time reasons: `syntax`, `badKey`, `keyExists`, `illegalEscapeCharacter`, `expectedHexCharacters`, `invalidHexCharacters`, `illegalUCSCode`, `invalidCharacter`). ### Example ```swift let document = """ owner = "dduan" [server] host = "127.0.0.1" """ let root = try TOMLTable(source: document) ``` ``` -------------------------------- ### Using TOMLTable in Codable Structs Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Example of defining a Codable struct containing a TOMLTable and decoding it using TOMLDecoder. ```swift struct Config: Codable { let owner: TOMLTable // works with TOMLDecoder } let config = try TOMLDecoder().decode(Config.self, from: tomlString) ``` -------------------------------- ### Array.init(_ tomlArray:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/index.md Converts a TOMLArray to a Swift array. ```APIDOC ## Array.init(_ tomlArray:) ### Description An extension initializer that creates a `[Any]` array from a `TOMLArray`. ### Usage ```swift let array = Array(tomlArray) ``` ``` -------------------------------- ### Decode String to Decodable Type Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLDecoder.md Decodes a TOML string into a Decodable instance. This example demonstrates using a custom key conversion strategy. ```swift public func decode(_ type: T.Type, from text: String) throws -> T ``` ```swift struct Client: Codable { let name: String let max_connections: Int } let text = """ name = "billing" max_connections = 100 """ let client = try TOMLDecoder(strategy: .init(key: .convertFromSnakeCase)).decode(Client.self, from: text) print(client.maxConnections) // if the property were named maxConnections ``` -------------------------------- ### Date.init(offsetDateTime:calendar:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/index.md Creates a Date from an OffsetDateTime and a calendar. ```APIDOC ## Date.init(offsetDateTime:calendar:) ### Description An extension initializer that creates a `Date` from an `OffsetDateTime` and a calendar. ### Usage ```swift let date = Date(offsetDateTime: offsetDateTime, calendar: calendar) ``` ``` -------------------------------- ### TOMLDecoder.Strategy.init(key:date:timeInterval:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/configuration.md Initializes a Strategy with key mapping, date strategy, and time interval strategy. The key strategy maps TOML table keys to Decodable property names, the date strategy determines how offset date-times become Date objects, and the time interval strategy interprets time intervals. ```APIDOC ## TOMLDecoder.Strategy.init(key:date:timeInterval:) ### Description Initializes a Strategy with key mapping, date strategy, and time interval strategy. The key strategy maps TOML table keys to Decodable property names, the date strategy determines how offset date-times become Date objects, and the time interval strategy interprets time intervals. ### Method Initializer ### Signature public init(key: KeyStrategy = .useOriginalKeys, date: DateStrategy = .gregorianCalendar, timeInterval: TimeIntervalStrategy = .since1970) ### Parameters - **key** (TOMLDecoder.KeyStrategy) - Optional - Default: .useOriginalKeys - Maps TOML table keys to Decodable property names. Cases: .useOriginalKeys, .convertFromSnakeCase, .custom((String) -> String). - **date** (TOMLDecoder.DateStrategy) - Optional - Default: .gregorianCalendar - How a TOML offset date-time becomes a Foundation.Date. Cases: .gregorianCalendar, .calendar(identifiedBy: Calendar.Identifier), .prolepticGregorianCalendar. - **timeInterval** (TOMLDecoder.TimeIntervalStrategy) - Optional - Default: .since1970 - How a TOML offset date-time or float becomes a TimeInterval/Double. Cases: .since1970, .since2001. ### Example let strategy = TOMLDecoder.Strategy(key: .convertFromSnakeCase, date: .prolepticGregorianCalendar, timeInterval: .since2001) ### Notes Strategy.default is Strategy(key: .useOriginalKeys, date: .gregorianCalendar, timeInterval: .since1970). Strategy effects depend on isLenient == true. ``` -------------------------------- ### Catch TOMLError from TOMLTable parsing Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/errors.md Example of catching a TOMLError when parsing a TOML string with TOMLTable. The description prints the line number and syntax error message. ```swift do { let table = try TOMLTable(source: brokenTOML) } catch let error as TOMLError { print(error.description) // "(Line 12) Syntax error: ..." } ``` -------------------------------- ### TOMLDecoder.init(isLenient:strategy:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/configuration.md Initializes a TOMLDecoder with optional leniency and strategy settings. The isLenient parameter controls type conversion flexibility, and strategy defines key mapping, date construction, and time interval interpretation. ```APIDOC ## TOMLDecoder.init(isLenient:strategy:) ### Description Initializes a TOMLDecoder with optional leniency and strategy settings. The isLenient parameter controls type conversion flexibility, and strategy defines key mapping, date construction, and time interval interpretation. ### Method Initializer ### Signature public init(isLenient: Bool = true, strategy: Strategy = .default) ### Parameters - **isLenient** (Bool) - Optional - Default: true - Whether the decoder converts a parsed TOML value to compatible Swift types during decoding. - **strategy** (TOMLDecoder.Strategy) - Optional - Default: Strategy.default - Options changing key mapping, Date construction, and TimeInterval interpretation. ### Example let decoder = TOMLDecoder(isLenient: false, strategy: .init(key: .convertFromSnakeCase, date: .prolepticGregorianCalendar, timeInterval: .since2001)) ### Notes Both parameters are stored as public vars, so configuration may also happen by mutation after initialization. ``` -------------------------------- ### TOMLDecoder.Strategy initializer with key, date, and timeInterval Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/configuration.md Public initializer for TOMLDecoder.Strategy. Defaults: key = .useOriginalKeys, date = .gregorianCalendar, timeInterval = .since1970. Strategy effects depend on isLenient == true. ```swift public init( key: KeyStrategy = .useOriginalKeys, date: DateStrategy = .gregorianCalendar, timeInterval: TimeIntervalStrategy = .since1970 ) ``` -------------------------------- ### Parse specific fields with TOMLTable Source: https://github.com/dduan/tomldecoder/blob/main/Sources/TOMLDecoder/TOMLDecoder.docc/GettingStarted.md Shows how to use lower-level APIs to access specific fields without Codable. It creates a TOMLTable from the TOML string, retrieves the 'owner' table, and then gets the 'name' string. ```swift // TOML is always a table at the root let rootTable = try TOMLTable(source: tomlString) // Get the `owner` table. It's a `TOMLTable` let owner = try rootTable.table(forKey: "owner") // Get a string from `owner` print(try owner.string(forKey: "name")) // Tom Preston-Werner ``` -------------------------------- ### init(from:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/OffsetDateTime.md Decodes an OffsetDateTime from a decoder. Uses a fast path for TOMLDecoder and falls back to the synthesized memberwise Decodable implementation for other decoders. ```APIDOC ## init(from:) ### Description Decodes an OffsetDateTime from a decoder. Uses a fast path for TOMLDecoder and falls back to the synthesized memberwise Decodable implementation for other decoders. ### Method Initializer ### Signature ```swift public init(from decoder: any Decoder) throws ``` ### Parameters - **decoder** (any Decoder) - Required - The decoder to read data from. ### Throws Throws an error if decoding fails. ``` -------------------------------- ### Catch TOMLError from TOMLDecoder decode Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/errors.md Example of catching errors from TOMLDecoder().decode. Parse failures are wrapped in DecodingError.dataCorrupted with the underlying TOMLError; semantic errors surface directly as TOMLError; container-level errors are caught as DecodingError. ```swift do { _ = try TOMLDecoder().decode(Config.self, from: brokenTOML) } catch DecodingError.dataCorrupted(let context) { let parseError = context.underlyingError as? TOMLError // the TOMLError, if TOML was invalid print(context.debugDescription) // "The given data was not valid TOML." } catch let error as TOMLError { // semantic reading errors (e.g. type mismatches during Decodable init) surface directly print(error.description) } catch DecodingError { // keyNotFound / valueNotFound / typeMismatch from the container layer } ``` -------------------------------- ### DateComponents.init(offsetDateTime:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/index.md Creates DateComponents from an OffsetDateTime. ```APIDOC ## DateComponents.init(offsetDateTime:) ### Description An extension initializer that creates a `DateComponents` from an `OffsetDateTime`. ### Usage ```swift let components = DateComponents(offsetDateTime: offsetDateTime) ``` ``` -------------------------------- ### LocalDate Initializers Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/DateTimeTypes.md Initializers for creating a LocalDate instance, including a validating version that throws TOMLError. ```swift public init(validatingYear year: UInt16, month: UInt8, day: UInt8) throws(TOMLError) // line 365 public init(year: UInt16, month: UInt8, day: UInt8) // line 381 ``` -------------------------------- ### Decode TOML offset date-time as Double using TimeIntervalStrategy Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/Strategies.md Shows how to decode a TOML offset date-time into a Double using the default .since1970 strategy. The example prints the epoch seconds as 1.7040672e9. Requires lenient decoding. ```swift struct Event: Codable { let occurredAt: Double // TOML offset date-time interpreted as epoch seconds } let toml = "occurredAt = 2024-01-01T00:00:00Z" // .since1970 (default): 1_704_067_200 as Double let event = try TOMLDecoder().decode(Event.self, from: toml) print(event.occurredAt) // 1.7040672e9 ``` -------------------------------- ### init(date:time:offset:features:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/OffsetDateTime.md Creates an offset date-time without validation. Use this initializer when you are certain the components are valid, or check isValid afterwards. ```APIDOC ## init(date:time:offset:features:) ### Description Creates an offset date-time without validation. Check `isValid` afterwards. ### Method Initializer ### Signature ```swift public init(date: LocalDate, time: LocalTime, offset: Int16, features: Features) ``` ### Parameters - **date** (LocalDate) - Required - The date component. - **time** (LocalTime) - Required - The time component. - **offset** (Int16) - Required - Offset from UTC in minutes; valid range [-1440, 1440]. - **features** (Features) - Required - Formatting details of the original string. ### Notes This initializer does not validate the components. Use `isValid` to check validity. ``` -------------------------------- ### Decode TOML into a Codable struct Source: https://github.com/dduan/tomldecoder/blob/main/Sources/TOMLDecoder/TOMLDecoder.docc/GettingStarted.md Shows how to decode a TOML string into a Swift Codable type using TOMLDecoder. The example includes a sample TOML string and a Config struct with nested types. The output prints the owner's name. ```swift import TOMLDecoder let tomlString = """ title = "TOML example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00-08:00 [database] enabled = true ports = [ 8000, 8001, 8002 ] temp_targets = { cpu = 79.5, case = 72.0 } """ // A normal `Codable` or `Decodable` type. struct Config: Codable { let title: String let owner: Owner let database: Database struct Owner: Codable { let name: String let dob: Date } struct Database: Codable { var enabled: Bool var ports: [Int] var tempTargets: [String: Double] } } let config = try TOMLDecoder().decode(Config.self, from: tomlString) print(config.owner.name) // Tom Preston-Werner ``` -------------------------------- ### init(validatingDate:time:offset:features:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/OffsetDateTime.md Creates an offset date-time with validation. Throws an error if any component is invalid. ```APIDOC ## init(validatingDate:time:offset:features:) ### Description Creates an offset date-time with validation. Throws an error if any component is invalid. ### Method Initializer ### Signature ```swift public init(validatingDate date: LocalDate, time: LocalTime, offset: Int16, features: Features) throws(TOMLError) ``` ### Parameters - **date** (LocalDate) - Required - The date component. - **time** (LocalTime) - Required - The time component. - **offset** (Int16) - Required - Offset from UTC in minutes; valid range [-1440, 1440]. - **features** (Features) - Required - Formatting details of the original string. ### Throws `TOMLError` with reason `.invalidDateTimeComponents(String)` when: - `date.isValid == false` - `time.isValid == false` - `offset` is outside [-1440, 1440] - `features` contain `lowercaseZ`/`uppercaseZ` while `offset != 0` ``` -------------------------------- ### string(forKey:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Returns the value of a key as a String. ```APIDOC ## Method: string(forKey:) ### Description Returns the value of `key` as a `String`. ### Declaration ```swift public func string(forKey key: String) throws(TOMLError) -> String ``` ### Parameters - **key** (String) - Required - Key to access. ### Throws - `TOMLError` if the key does not exist (`.keyNotFoundInTable`) or the value is not a string (`.typeMismatch` via `Token.unpackString`, which throws `.invalidString` or `.typeMismatch` for malformed content). ### Return Value - **String** - The string value associated with the key. ``` -------------------------------- ### DateComponents.init(offsetDateTime:) initializer Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/DateTimeTypes.md Creates Foundation.DateComponents containing literal components from an OffsetDateTime, excluding the calendar component. ```swift public init(offsetDateTime: OffsetDateTime) ``` -------------------------------- ### Date.init(offsetDateTime:calendar:) initializer Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/DateTimeTypes.md Constructs a Date from an OffsetDateTime using a specified calendar. Note that the default Gregorian calendar is not proleptic; use timeIntervalSince2001 for proleptic values. ```swift public init(offsetDateTime: OffsetDateTime, calendar: Calendar = Calendar(identifier: .gregorian)) ``` ```swift import Foundation let table = try TOMLTable(source: "moment = 2024-01-02T03:04:05+02:00") let moment = try table.offsetDateTime(forKey: "moment") let date = Date(offsetDateTime: moment) // Gregorian calendar let components = DateComponents(offsetDateTime: moment) // literal components let proleptic = Date(timeIntervalSinceReferenceDate: moment.timeIntervalSince2001) ``` -------------------------------- ### init(source:) (UTF-8 collection) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Creates a root-level TOMLTable from a TOML document represented as UTF-8 code units, such as Data read from a UTF-8 text file. Throws TOMLError if the document is invalid or the bytes are not valid UTF-8. ```APIDOC ## init(source:) (UTF-8 collection) ### Description Creates a root-level TOMLTable from a TOML document represented as UTF-8 code units, such as Data read from a UTF-8 text file. Throws TOMLError if the document is invalid or the bytes are not valid UTF-8. ### Method Initializer ### Signature ```swift public init(source: some Collection) throws(TOMLError) ``` ### Parameters - **source** (some Collection) - Required - The TOML document encoded in UTF-8 ### Throws TOMLError. If the bytes are not valid UTF-8, throws TOMLError with reason `.invalidUTF8`. ### Example ```swift import Foundation let data = try Data(contentsOf: URL(fileURLWithPath: "config.toml")) let table = try TOMLTable(source: data) ``` ``` -------------------------------- ### Add TOMLDecoder product to target dependencies Source: https://github.com/dduan/tomldecoder/blob/main/Sources/TOMLDecoder/TOMLDecoder.docc/GettingStarted.md Add this line to a target's dependencies in Package.swift to link the TOMLDecoder product. ```swift .product(name: "TOMLDecoder", package: "TOMLDecoder"), ``` -------------------------------- ### Initialize TOMLTable from a String Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Creates a root-level TOMLTable by parsing a TOML document from a String. Throws TOMLError for parse-time errors such as syntax, badKey, keyExists, illegalEscapeCharacter, expectedHexCharacters, invalidHexCharacters, illegalUCSCode, and invalidCharacter. ```swift public init(source: String) throws(TOMLError) ``` -------------------------------- ### LocalDateTime Initializers Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/DateTimeTypes.md Initializers for the LocalDateTime struct, including a validating version that throws TOMLError. ```swift public init(date: LocalDate, time: LocalTime) // line 229, no validation public init(from decoder: any Decoder) throws // line 234 public init(validatingDate date: LocalDate, time: LocalTime) throws(TOMLError) // line 250 ``` -------------------------------- ### localDateTime(forKey:exactMatch:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Returns the value of a key as a LocalDateTime. ```APIDOC ## Method: localDateTime(forKey:exactMatch:) ### Description Returns the value of `key` as a `LocalDateTime`. ### Declaration ```swift public func localDateTime(forKey key: String, exactMatch: Bool = true) throws(TOMLError) -> LocalDateTime ``` ### Parameters - **key** (String) - Required - Key to access. - **exactMatch** (Bool) - Optional - Default: `true`. When `false`, an offset date-time value yields its local date-time (dropping the offset). ### Throws - `TOMLError` (`.keyNotFoundInTable` or `.typeMismatch` with expected `"local date-time"`). ### Return Value - **LocalDateTime** - The local date-time value associated with the key. ``` -------------------------------- ### Parse TOML with TOMLTable(source:) Source: https://github.com/dduan/tomldecoder/blob/main/Sources/TOMLDecoder/TOMLDecoder.docc/DeserializingTOML.md Create a TOMLTable from a TOML string to parse a document. The root of a TOML document is always a table, so this is the entry point for deserialization. ```swift let tomlString = """ answer = 42 questions = ["why?", "how?", "ya?"] """ let rootTable = try TOMLTable(source: tomlString) ``` -------------------------------- ### localTime(forKey:exactMatch:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Returns the value of a key as a LocalTime. ```APIDOC ## Method: localTime(forKey:exactMatch:) ### Description Like `localDateTime`, but yields a `LocalTime`. With `exactMatch == false`, an offset date-time or local date-time value yields its time portion. ### Declaration ```swift public func localTime(forKey key: String, exactMatch: Bool = true) throws(TOMLError) -> LocalTime ``` ### Parameters - **key** (String) - Required - Key to access. - **exactMatch** (Bool) - Optional - Default: `true`. When `false`, an offset date-time or local date-time value yields its time portion. ### Throws - `TOMLError` (`.keyNotFoundInTable` or `.typeMismatch`). ### Return Value - **LocalTime** - The local time value associated with the key. ``` -------------------------------- ### LocalTime Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/DateTimeTypes.md Documentation for the LocalTime struct, including its initializers, properties, and validation behavior. ```APIDOC ## LocalTime ### Description A local time with hour, minute, second, and nanosecond components. Fractional seconds are stored as nanoseconds. ### Initializers ```swift public init(validatingHour hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) throws(TOMLError) public init(hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) ``` ### Computed Properties ```swift public var isValid: Bool public var description: String ``` ### Stored Properties | Property | Type | Description | |----------|------|-------------| | `hour` | `UInt8` | Hour component | | `minute` | `UInt8` | Minute component | | `second` | `UInt8` | Second component | | `nanosecond` | `UInt32` | Fractional second, in nanoseconds | ### Validation The validating initializer throws `TOMLError` (`.invalidDateTimeComponents`) when `isValid` is `false`. ### Description Format `"HH:MM:SS[.fraction]"` with trailing zeros trimmed. ``` -------------------------------- ### Initialize TOMLDecoder Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLDecoder.md The initializer accepts optional parameters for leniency and decoding strategy. Properties can also be modified after initialization. ```swift public init(isLenient: Bool = true, strategy: Strategy = .default) ``` ```swift var decoder = TOMLDecoder() decoder.strategy = .init(key: .convertFromSnakeCase) ``` -------------------------------- ### LocalDateTime Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/DateTimeTypes.md Documentation for the LocalDateTime struct, including its initializers, properties, and validation behavior. ```APIDOC ## LocalDateTime ### Description A local date-time (no offset) with date and time components. Stores fractional seconds to nanosecond precision. ### Initializers ```swift public init(date: LocalDate, time: LocalTime) public init(from decoder: any Decoder) throws public init(validatingDate date: LocalDate, time: LocalTime) throws(TOMLError) ``` ### Computed Properties ```swift public var isValid: Bool public var description: String ``` ### Stored Properties | Property | Type | Description | |----------|------|-------------| | `date` | `LocalDate` | Date component | | `time` | `LocalTime` | Time component | ### Validation The validating initializer throws `TOMLError` (`.invalidDateTimeComponents`) when `date.isValid` or `time.isValid` is `false`. ### Description Format `"\(date.description)T\(time.description)"` ``` -------------------------------- ### Mutating TOMLDecoder properties after initialization Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/configuration.md Shows how to change isLenient and strategy.key after creating a TOMLDecoder instance. Useful when you need to adjust configuration without reinitializing. ```swift var decoder = TOMLDecoder() decoder.isLenient = false decoder.strategy.key = .convertFromSnakeCase ``` -------------------------------- ### Handle Decoding Errors Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLDecoder.md Demonstrates how to catch and inspect errors during the decoding process, including invalid TOML syntax and type mismatches. ```swift // Error handling: invalid TOML surfaces as a DecodingError wrapper. do { _ = try TOMLDecoder().decode(Client.self, from: "key = ") // invalid TOML } catch DecodingError.dataCorrupted(let context) { print(context.debugDescription) // "The given data was not valid TOML." print(context.underlyingError!) // a TOMLError with the parse detail } // Type-level errors: let Swift's error handling pick the kind you care about. do { _ = try TOMLDecoder(isLenient: false).decode(Client.self, from: "max_connections = \"x\"") } catch { print(error) // DecodingError or TOMLError describing the mismatch ``` -------------------------------- ### TOMLDecoder initializer with isLenient and strategy Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/configuration.md Public initializer for TOMLDecoder. Defaults: isLenient = true, strategy = .default. Both parameters are stored as public vars, so they can be mutated after initialization. ```swift public init(isLenient: Bool = true, strategy: Strategy = .default) ``` -------------------------------- ### TOMLTable Dictionary Conversion Initializer Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Initializer definition for creating a [String: Any] dictionary from a TOMLTable. ```swift public init(_ tomlTable: TOMLTable) throws(TOMLError) // line 442 ``` -------------------------------- ### LocalTime Initializers Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/DateTimeTypes.md Initializers for the LocalTime struct, including a validating version that checks component ranges. ```swift public init(validatingHour hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) throws(TOMLError) // line 294 public init(hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) // line 311 ``` -------------------------------- ### Initialize TOMLTable from a UTF-8 collection Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Creates a root-level TOMLTable from a TOML document represented as UTF-8 code units, such as Data read from a UTF-8 text file. Throws TOMLError with reason .invalidUTF8 if the bytes are not valid UTF-8. ```swift public init(source: some Collection) throws(TOMLError) ``` -------------------------------- ### Initialize OffsetDateTime Features with rawValue Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/OffsetDateTime.md Initializes the Features OptionSet using a raw UInt8 value. ```swift public init(rawValue: UInt8) // line 191 ``` -------------------------------- ### localDate(forKey:exactMatch:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Returns the value of a key as a LocalDate. ```APIDOC ## Method: localDate(forKey:exactMatch:) ### Description Like `localDateTime`, but yields a `LocalDate`. With `exactMatch == false`, an offset date-time or local date-time value yields its date portion. ### Declaration ```swift public func localDate(forKey key: String, exactMatch: Bool = true) throws(TOMLError) -> LocalDate ``` ### Parameters - **key** (String) - Required - Key to access. - **exactMatch** (Bool) - Optional - Default: `true`. When `false`, an offset date-time or local date-time value yields its date portion. ### Throws - `TOMLError` (`.keyNotFoundInTable` or `.typeMismatch`). ### Return Value - **LocalDate** - The local date value associated with the key. ``` -------------------------------- ### Decoding with convertFromSnakeCase strategy Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/Strategies.md Shows how to decode a TOML document using the KeyStrategy.convertFromSnakeCase to map snake_case keys to camelCase properties. The output prints the decoded value. Requires the Swift Codable type and a TOMLDecoder instance. ```swift let toml = """ first_name = "Tom" """ struct Person: Codable { let firstName: String } let decoder = TOMLDecoder(strategy: .init(key: .convertFromSnakeCase)) let person = try decoder.decode(Person.self, from: toml) print(person.firstName) // Tom ``` -------------------------------- ### integer(forKey:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Returns the value of a key as an Int64. ```APIDOC ## Method: integer(forKey:) ### Description Returns the value of `key` as an `Int64` (TOML's definitive integer type). ### Declaration ```swift public func integer(forKey key: String) throws(TOMLError) -> Int64 ``` ### Parameters - **key** (String) - Required - Key to access. ### Throws - `TOMLError` (`.keyNotFoundInTable` or `.invalidInteger`). ### Return Value - **Int64** - The integer value associated with the key. ``` -------------------------------- ### Access strategy property Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLDecoder.md The strategy property allows customization of key mapping, date construction, and time interval interpretation. ```swift public var strategy: Strategy ``` -------------------------------- ### float(forKey:) Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Returns the value of a key as a Double. ```APIDOC ## Method: float(forKey:) ### Description Returns the value of `key` as a `Double` (TOML's definitive float type). ### Declaration ```swift public func float(forKey key: String) throws(TOMLError) -> Double ``` ### Parameters - **key** (String) - Required - Key to access. ### Throws - `TOMLError` (`.keyNotFoundInTable` or `.invalidFloat`). ### Return Value - **Double** - The float value associated with the key. ``` -------------------------------- ### Declare TOMLDecoder dependency in MODULE.bazel Source: https://github.com/dduan/tomldecoder/blob/main/Sources/TOMLDecoder/TOMLDecoder.docc/GettingStarted.md Include this line in your MODULE.bazel to use TOMLDecoder from the Bazel Central Registry. ```bazel bazel_dep(name = 'swift-tomldecoder', version = '0.4.5') ``` -------------------------------- ### TOMLTable string(forKey:) method Source: https://github.com/dduan/tomldecoder/blob/main/_autodocs/api-reference/TOMLTable.md Declares the `string(forKey:)` method that returns a `String` for the given key. Throws `TOMLError` if the key is not found or the value is not a string. ```swift public func string(forKey key: String) throws(TOMLError) -> String ```