Swiftpack.co -  LebJe/TOMLKit as Swift Package
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
LebJe/TOMLKit
A small, simple TOML parser for Swift. Powered by toml++.
.package(url: "https://github.com/LebJe/TOMLKit.git", from: "0.1.2")

TOMLKit

A small, simple TOML parser for Swift. Powered by toml++.

Swift 5.4 SPM Compatible Build and Test

TOMLKit is a Swift wrapper around toml++, allowing you to read and write TOML files in Swift.

Table of Contents

Created by gh-md-toc

Documentation is available here.

Installation

Swift Package Manager

Add this to the dependencies array in Package.swift:

.package(url: "https://github.com/LebJe/TOMLKit.git", from: "0.1.1")

Also add this to the targets array in the aforementioned file:

.product(name: "TOMLKit", package: "TOMLKit")

Usage

Once you have installed TOMLKit, you will usually start with a TOMLTable, or by decoding a TOML document into a Swift structure.

Creating TOML Values

Tables

TOML tables are key-value pairs, similar to a Swift Dictionary. They can also be embedded inside one another.

To create a empty TOMLTable, use the TOMLTable.init(inline:) initializer, where inline makes the table an inline table:

# `inline` is true.
inlineTable = { field1 = "", ... }

or a regular table:

# `inline` is false.
[regularTable]
field1 = ""
...

NOTE

Use myTable.inline = true/false to make a table inline/not inline, and myTable.inline to check if a table is inlined.


To create a TOMLTable with values, use one of the below methods:

From a Dictionary
let table = TOMLTable(["string": "Hello, World!", "int": 345025, "double": 025307.350])

// Or use `TOMLTable`'s `ExpressibleByDictionaryLiteral` conformance.
let table = ["string": "Hello, World!", "int": 345025, "double": 025307.350] as TOMLTable
From a TOML String
let toml = """
string = "Hello, World!"
int = 523053
double = 3250.34
"""

do {
   let table = try TOMLTable(string: toml)
} catch let error as TOMLParseError {
   // TOMLParseError occurs when the TOML document is invalid.

   /// `error.source.begin` contains the line and column where the error started,
   /// and `error.source.end` contains the line where the error ended.
    print(error.source.begin)
    print(error.source.end)
}

To insert values, make sure the value conforms to TOMLValueConvertible, then use the subscript, or the insert(_ newElement:at:) method:

let table = TOMLTable()

table["string"] = "Hello, World!"
table.insert(127, at: "int")
table["table"] = TOMLTable(["string 1": "Hello, Again!"], inline: true)
table["table"] = TOMLTable(["string 2": "Hello, Again!"], inline: false)

// Insert an integer using an octal representation.
table.insert(TOMLInt(0o755, options: .formatAsOctal), at: "octalInt")
Conversion
let table: TOMLTable = ...

// Convert to TOML using default settings.
let toml1 = table.convert()

// Convert to JSON using default settings.
let json = table.convert(to: .json)

// Convert to TOML with custom settings.
let toml2 = table.convert(to: .toml, options: [.quoteDateAndTimes, .allowMultilineStrings])

Arrays

TOML arrays are similar to a Swift Array. They can be embedded inside one another.

To create a empty TOMLArray, use the TOMLArray.init initializer.

To create a TOMLArray with values, use one of the below methods:

let array = TOMLArray(
	[
		"Hello, World!",
		"Hello, Again!",
		3294923.tomlInt,
		2350.53,
		TOMLTable(["string": "string 1"])
	]
)

// Or use `TOMLArray`'s `ExpressibleByArrayLiteral` conformance.
let array = [
	"Hello, World!",
	"Hello, Again!",
	3294923.tomlInt,
	2350.53,
	TOMLTable(["string": "string 1"])
] as TOMLArray

To insert values, use the subscript, the append(_ value:) method, or the insert(_ value:at:) method:

let array = TOMLArray()

array.append("Hello, World")
array.insert(TOMLInt(0x123abc, options: .formatAsHexadecimal), at: 1)
array[0] = TOMLTable(["double": 02734.23])

Dates

// Create a date from numerical values.
let date = TOMLDate(year: 2021, month: 6, day: 10)

// Create a date from `Foundation.Date`
import Foundation

let date2 = TOMLDate(date: Date())
let table = TOMLTable(["Date1": date, "Date2": date2])

Times

// Create a time from numerical values.
let time = TOMLTime(hour: 12, minute: 27, second: 49)
let table = TOMLTable(["time": time])

Data

import Foundation

let data = Data([0x01, 0x02, 0x03])

// `data` will be encoded as Base64.
let table = TOMLTable(["data": data])

Integers

Integers that don't need to be formatted will be converted to a TOMLInt automatically. Use the TOMLInt.init(_ value:options:) initializer to format integers as octal, hexadecimal, or binary values.

Retrieving TOML values

From Tables

let table: TOMLTable = ...

if let string = table["string"]?.string {
   print(string)
}

if let bool = table["bool"]?.bool {
   print(bool)
}

if let double = table["InnerTable"]?.tomlValue["InnerInnerTable"]?["InnerInnerInnerTable"]?.double {
print(double)
}

...

From Arrays

let array: TOMLArray = ...

if let string = array[0].string? {
   print(string)
}

if let bool = array[1].bool? {
   print(bool)
}

if let double = array[2][0].double? {
   print(double)
}

for value in array {
   print(value)
}

Encoding struct to TOML

struct TestStruct: Encodable {
	let string: String = "Hello, World!"
	let int: Int = 200823
}

let toml = try TOMLEncoder().encode(TestStruct())

print(toml)

Decoding TOML to struct

struct TestStruct: Decodable {
	let string: String
	let int: Int
}

let testStruct = try TOMLDecoder().decode(TestStruct.self, from: "string = \"Hello, World!\"\nint = 405347")

print(testStruct)

Dependencies

Licenses

The toml++ license is available in the tomlplusplus directory in the LICENSE file.

Contributing

Before committing, please install pre-commit, swift-format, and Prettier then install the pre-commit hook:

$ brew bundle # install the packages specified in Brewfile
$ pre-commit install

# Commit your changes.

To install pre-commit on other platforms, refer to the documentation.

GitHub

link
Stars: 0
Last commit: 5 days ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Release Notes

Support for Encoding and Decoding `Foundation.Data`
5 days ago

Changelog

Added

  • Support for encoding and decoding Foundation.Data in Base64 or a custom format.

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API