Working with YAML in Swift (iOS/macOS): Yams Library
YAML (YAML Ain't Markup Language) is a convenient data serialization format often used for configuration files, dependency descriptions (e.g., docker-compose.yml), and projects requiring a readable and concise data structure. In the Apple ecosystem, several libraries exist for working with YAML in Swift, but the most popular and stable is Yams — a fast and easy-to-use library written in pure Swift.
What is Yams?
Yams is an open-source library that provides full support for parsing and serializing YAML in Swift. It is compatible with iOS, macOS, tvOS, and watchOS. Yams supports the YAML 1.2 specification and allows converting YAML strings into Swift structures (dictionaries, arrays, strings, numbers, booleans) and back.
Key features of Yams:
- Parsing a YAML string into
Any(typically[String: Any]or[Any]). - Serializing Swift objects back to YAML.
- Support for nested structures, arrays, and multiple documents.
- Error handling with detailed messages.
- Fully compatible with Swift Package Manager (SPM) and CocoaPods.
Installing Yams in Your Project
You can install Yams via Swift Package Manager (recommended) or CocoaPods.
Via Swift Package Manager
- In Xcode, select File → Add Packages.
- Paste the repository URL:
https://github.com/jpsim/Yams.git - Choose a version (latest stable is recommended) and click Add Package.
Or add the dependency in Package.swift:
// swift-tools-version:5.7import PackageDescription
let package = Package( name: "MyProject", dependencies: [ .package(url: "https://github.com/jpsim/Yams.git", from: "5.0.0") ], targets: [ .target( name: "MyProject", dependencies: ["Yams"]) ])Via CocoaPods
Add the line to your Podfile:
pod 'Yams', '~> 5.0'Then run pod install.
Basic Usage: Parsing YAML
After installation, import the library and use Yams.load(yaml:) to parse a string.
import Yams
let yamlString = """name: Swifttype: languageversions: - 5.5 - 5.6 - 5.7features: protocol_oriented: true value_semantics: true"""
do { if let data = try Yams.load(yaml: yamlString) as? [String: Any] { print("Name: \\(data["name"] ?? "")") print("Versions: \\(data["versions"] ?? [])") if let features = data["features"] as? [String: Bool] { print("Protocol oriented: \\(features["protocol_oriented"] ?? false)") } }} catch { print("YAML parsing error: \\(error.localizedDescription)")}Output:
Name: SwiftVersions: [5.5, 5.6, 5.7]Protocol oriented: trueSerializing Swift Objects to YAML
For reverse conversion, use Yams.dump(object:):
import Yams
let dictionary: [String: Any] = [ "app": "MyApp", "version": 2.0, "features": ["dark_mode", "notifications"], "settings": [ "autosave": true, "timeout": 30 ]]
do { let yamlString = try Yams.dump(object: dictionary) print(yamlString)} catch { print("Serialization error: \\(error.localizedDescription)")}Output:
app: MyAppfeatures: - dark_mode - notificationssettings: autosave: true timeout: 30