### Install SwiftSemver via Swift Package Manager Source: https://context7.com/gwynne/swift-semver/llms.txt Add SwiftSemver as a dependency in your Package.swift file to include it in your project. ```swift import PackageDescription let package = Package( name: "MyApp", dependencies: [ .package(url: "https://github.com/gwynne/swift-semver.git", from: "1.0.0"), ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "SwiftSemver", package: "swift-semver"), ] ), ] ) ``` -------------------------------- ### SemanticVersion Description and Debug Description Source: https://context7.com/gwynne/swift-semver/llms.txt Shows how to serialize a SemanticVersion back into a canonical semver string using `description` and get a verbose representation for debugging with `debugDescription`. ```swift import SwiftSemver let ver = SemanticVersion(1, 2, 3, prereleaseIdentifiers: ["beta", "1"], buildMetadataIdentifiers: ["20240315"]) // Standard string representation (CustomStringConvertible / LosslessStringConvertible) print(ver.description) // "1.2.3-beta.1+20240315" print("\(ver)") // "1.2.3-beta.1+20240315" print(String(ver)) // "1.2.3-beta.1+20240315" // Debug representation (CustomDebugStringConvertible) print(ver.debugDescription) // "Version:{Major: 1 Minor: 2 Patch: 3 Prerelease identifiers: [beta, 1] Build metadata identifiers: [20240315]}" // Round-trip: description → parse → description let roundTripped = SemanticVersion(string: ver.description)! print(roundTripped == ver) // true ``` -------------------------------- ### SemanticVersion Comparable Conformance Source: https://context7.com/gwynne/swift-semver/llms.txt Demonstrates the precedence ordering of SemanticVersion instances according to the semver specification. Build metadata does not influence ordering. ```swift import SwiftSemver // Basic ordering print(SemanticVersion("1.0.0")! < SemanticVersion("2.0.0")!) // true print(SemanticVersion("1.2.0")! > SemanticVersion("1.1.9")!) // true // Pre-release versions sort below their release counterpart print(SemanticVersion("1.0.0-rc.9")! < SemanticVersion("1.0.0")!) // true // Numeric identifiers compared numerically, not lexicographically print(SemanticVersion("1.0.0-rc.2")! < SemanticVersion("1.0.0-rc.10")!) // true (not false) // Alphanumeric always beats numeric in pre-release print(SemanticVersion("1.0.0-10")! < SemanticVersion("1.0.0-a")!) // true // Build metadata does not affect ordering let a = SemanticVersion("1.0.0-alpha.1+snafu")! let b = SemanticVersion("1.0.0-alpha.1+fubar")! print(a <= b && b <= a) // true — they are precedence-equal // Sorting a release train — reproduces the spec's own example let versions = [ "1.0.0-beta.11", "1.0.0-alpha.beta", "1.0.0", "1.0.0-rc.1", "1.0.0-alpha", "1.0.0-beta.2", "1.0.0-alpha.1", "1.0.0-beta", ].compactMap { SemanticVersion($0) }.sorted() print(versions.map(\.description)) // ["1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", // "1.0.0-beta", "1.0.0-beta.2", "1.0.0-beta.11", // "1.0.0-rc.1", "1.0.0"] ``` -------------------------------- ### Memberwise Initializer Source: https://context7.com/gwynne/swift-semver/llms.txt Creates a SemanticVersion directly from its integer components (major, minor, patch) and optional prerelease and build metadata identifiers. All integer components must be non-negative. Prerelease identifiers must adhere to specific formatting rules, and build metadata identifiers must be non-empty. ```APIDOC ## `SemanticVersion.init(_:_:_:prereleaseIdentifiers:buildMetadataIdentifiers:)` ### Description Creates a `SemanticVersion` directly from its integer components and optional identifier arrays. ### Parameters - **major** (Int) - The major version component. - **minor** (Int) - The minor version component. - **patch** (Int) - The patch version component. - **prereleaseIdentifiers** (Array?) - Optional array of prerelease identifiers. - **buildMetadataIdentifiers** (Array?) - Optional array of build metadata identifiers. ### Usage Examples ```swift import SwiftSemver // Simple release version let v1 = SemanticVersion(1, 0, 0) // Pre-release version let beta = SemanticVersion(2, 0, 0, prereleaseIdentifiers: ["beta", "1"]) // Version with build metadata let build = SemanticVersion(1, 4, 2, buildMetadataIdentifiers: ["20240315", "abc1234"]) // Full version: pre-release + build metadata let full = SemanticVersion(3, 0, 0, prereleaseIdentifiers: ["rc", "2"], buildMetadataIdentifiers: ["arm64"]) // Accessing components print(full.major) // 3 print(full.minor) // 0 print(full.patch) // 0 print(full.prereleaseIdentifiers) // ["rc", "2"] print(full.buildMetadataIdentifiers) // ["arm64"] ``` ``` -------------------------------- ### Safe SemanticVersion Constructor Helper in Swift Source: https://context7.com/gwynne/swift-semver/llms.txt A helper function `makeVersion` demonstrates how to safely construct a `SemanticVersion` by validating prerelease and build metadata identifiers using the respective extension properties before attempting to create the version object. ```swift // Example: safe constructor helper func makeVersion(_ major: Int, _ minor: Int, _ patch: Int, prerelease: [String], build: [String]) -> SemanticVersion? { guard prerelease.allSatisfy(\.semver_isValidPrereleaseIdentifier), build.allSatisfy(\.semver_isValidBuildMetadataIdentifier) else { return nil } return SemanticVersion(major, minor, patch, prereleaseIdentifiers: prerelease, buildMetadataIdentifiers: build) } print(makeVersion(1, 0, 0, prerelease: ["rc", "1"], build: ["arm64"])) // Optional(1.0.0-rc.1+arm64) print(makeVersion(1, 0, 0, prerelease: ["01"], build: [])) // nil ``` -------------------------------- ### SemanticVersion Codable Conformance Source: https://context7.com/gwynne/swift-semver/llms.txt Illustrates encoding SemanticVersion instances to JSON strings and decoding them back. Decoding fails with `DecodingError.dataCorrupted` for invalid version strings. ```swift import Foundation import SwiftSemver struct AppConfig: Codable { let minRequiredVersion: SemanticVersion let currentVersion: SemanticVersion } // Encoding let config = AppConfig( minRequiredVersion: SemanticVersion(1, 5, 0)!, currentVersion: SemanticVersion(string: "2.0.0-rc.1+build.42")! ) let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let data = try encoder.encode(config) print(String(decoding: data, as: UTF8.self)) // { // "minRequiredVersion" : "1.5.0", // "currentVersion" : "2.0.0-rc.1+build.42" // } // Decoding let json = """{"minRequiredVersion": "1.5.0", "currentVersion": "2.0.0-rc.1+build.42"}""" let decoded = try JSONDecoder().decode(AppConfig.self, from: Data(json.utf8)) print(decoded.currentVersion.prereleaseIdentifiers) // ["rc", "1"] // Invalid version string in JSON throws DecodingError.dataCorrupted let bad = #"{"minRequiredVersion": "not-a-version", "currentVersion": "1.0.0"}"# do { _ = try JSONDecoder().decode(AppConfig.self, from: Data(bad.utf8)) } catch DecodingError.dataCorrupted(let ctx) { print(ctx.debugDescription) // "Invalid semantic version: not-a-version" } ``` -------------------------------- ### Parse SemanticVersion from String Source: https://context7.com/gwynne/swift-semver/llms.txt Use the failable initializers `init(string:)` or `init(_:)` to parse a string into a `SemanticVersion`. These return `nil` for invalid input, allowing for graceful error handling. ```swift import SwiftSemver // Successful parses let v = SemanticVersion("2.1.0")! print(v.major, v.minor, v.patch) // 2 1 0 let prerelease = SemanticVersion(string: "1.0.0-alpha.1")! print(prerelease.prereleaseIdentifiers) // ["alpha", "1"] let withBuild = SemanticVersion(string: "1.0.0-beta+exp.sha.5114f85")! print(withBuild.buildMetadataIdentifiers) // ["exp", "sha", "5114f85"] // Graceful nil handling for invalid input let invalid = [ "", // empty "1.2", // missing patch "1.2.3.4", // too many components "1.2.3-01", // leading zero in numeric pre-release identifier "1.2.3-!", // invalid character ] for str in invalid { if let ver = SemanticVersion(str) { print("Parsed: \(ver)") } else { print("Invalid: '\(str)'") // all print here } } // Parsing from a Substring (using the generic init(string:)) let rawHeader = "X-App-Version: 4.2.0-rc.1" if let sub = rawHeader.split(separator: " ").last, let ver = SemanticVersion(string: sub) { print(ver) // "4.2.0-rc.1" } ``` -------------------------------- ### String Parsing Initializers Source: https://context7.com/gwynne/swift-semver/llms.txt Failable initializers that parse a string into a SemanticVersion object according to the Semantic Versioning 2.0.0 grammar. Returns `nil` if the input string does not conform to the grammar. ```APIDOC ## `SemanticVersion.init(string:)` / `SemanticVersion.init(_:)` ### Description Parses a string according to the Semantic Versioning 2.0.0 grammar. Returns `nil` for invalid input. ### Parameters - **string** (StringProtocol) - The string to parse. ### Usage Examples ```swift import SwiftSemver // Successful parses let v = SemanticVersion("2.1.0")! print(v.major, v.minor, v.patch) // 2 1 0 let prerelease = SemanticVersion(string: "1.0.0-alpha.1")! print(prerelease.prereleaseIdentifiers) // ["alpha", "1"] let withBuild = SemanticVersion(string: "1.0.0-beta+exp.sha.5114f85")! print(withBuild.buildMetadataIdentifiers) // ["exp", "sha", "5114f85"] // Graceful nil handling for invalid input let invalid = [ "", // empty "1.2", // missing patch "1.2.3.4", // too many components "1.2.3-01", // leading zero in numeric pre-release identifier "1.2.3-!", // invalid character ] for str in invalid { if let ver = SemanticVersion(str) { print("Parsed: \(ver)") } else { print("Invalid: '\(str)'") // all print here } } // Parsing from a Substring let rawHeader = "X-App-Version: 4.2.0-rc.1" if let sub = rawHeader.split(separator: " ").last, let ver = SemanticVersion(string: sub) { print(ver) // "4.2.0-rc.1" } ``` ``` -------------------------------- ### Create SemanticVersion using Memberwise Initializer Source: https://context7.com/gwynne/swift-semver/llms.txt Use the memberwise initializer to create a `SemanticVersion` directly from its integer components and optional identifier arrays. Ensure components are non-negative and identifiers follow the spec. ```swift import SwiftSemver // Simple release version let v1 = SemanticVersion(1, 0, 0) print(v1) // "1.0.0" // Pre-release version with multiple identifiers let beta = SemanticVersion(2, 0, 0, prereleaseIdentifiers: ["beta", "1"]) print(beta) // "2.0.0-beta.1" // Version with build metadata (e.g., CI build number + commit hash) let build = SemanticVersion(1, 4, 2, buildMetadataIdentifiers: ["20240315", "abc1234"]) print(build) // "1.4.2+20240315.abc1234" // Full version: pre-release + build metadata let full = SemanticVersion(3, 0, 0, prereleaseIdentifiers: ["rc", "2"], buildMetadataIdentifiers: ["arm64"]) print(full) // "3.0.0-rc.2+arm64" // Accessing components print(full.major) // 3 print(full.minor) // 0 print(full.patch) // 0 print(full.prereleaseIdentifiers) // ["rc", "2"] print(full.buildMetadataIdentifiers) // ["arm64"] ``` -------------------------------- ### Validate Build Metadata Identifiers in Swift Source: https://context7.com/gwynne/swift-semver/llms.txt Use `semver_isValidBuildMetadataIdentifier` to validate build metadata strings. Rules include non-empty, only ASCII letters, digits, and '-', with leading zeros permitted. ```swift // Build metadata identifier rules: // - Non-empty // - Only ASCII letters, digits, and "-" // - No leading-zero restriction print("001".semver_isValidBuildMetadataIdentifier) // true — leading zeros allowed print("build-42".semver_isValidBuildMetadataIdentifier) // true print("".semver_isValidBuildMetadataIdentifier) // false — empty print("sha@abc".semver_isValidBuildMetadataIdentifier) // false — invalid char ``` -------------------------------- ### Validate Prerelease Identifiers in Swift Source: https://context7.com/gwynne/swift-semver/llms.txt Use `semver_isValidPrereleaseIdentifier` to check if a string conforms to prerelease identifier rules: non-empty, only ASCII letters, digits, and '-', and no leading zeros for purely numeric identifiers (except '0'). ```swift import SwiftSemver // Prerelease identifier rules: // - Non-empty // - Only ASCII letters, digits, and "-" // - Purely numeric: no leading zeros (except bare "0") print("alpha".semver_isValidPrereleaseIdentifier) // true print("rc-1".semver_isValidPrereleaseIdentifier) // true print("0".semver_isValidPrereleaseIdentifier) // true print("42".semver_isValidPrereleaseIdentifier) // true print("01".semver_isValidPrereleaseIdentifier) // false — leading zero print("".semver_isValidPrereleaseIdentifier) // false — empty print("rc!".semver_isValidPrereleaseIdentifier) // false — invalid char ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.