一个 Swift 包,提供了一个轻量级、安全的 Foundation.OperatingSystemVersion
封装,并增加了 JSON 编码/解码和字符串解析等额外功能。
将以下内容添加到你的 Package.swift
文件中
dependencies: [
.package(url: "https://github.com/yourusername/OSVer.git", from: "1.0.0")
]
// Initialize with major and minor versions (patch defaults to 0)
let version1 = OSVer(major: 1, minor: 2)
// Initialize with all components
let version2 = OSVer(major: 1, minor: 2, patch: 3)
// Initialize using OperatingSystemVersion style
let version3 = OSVer(majorVersion: 1, minorVersion: 2, patchVersion: 3)
// Initialize from OperatingSystemVersion
let osVersion = OperatingSystemVersion(majorVersion: 1, minorVersion: 2, patchVersion: 3)
let version4 = OSVer(osVersion)
// Parse from string
let version = try OSVer(string: "1.2.3")
// Parse without patch version (defaults to 0)
let version = try OSVer(string: "1.2") // equivalent to "1.2.0"
// Encode as object (default)
let encoder = JSONEncoder()
let data = try encoder.encode(version)
// Result: {"major":1,"minor":2,"patch":3}
// Encode as string
encoder.userInfo[OSVer.encodingFormatKey] = OSVer.EncodingFormat.string
let stringData = try encoder.encode(version)
// Result: "1.2.3"
// Decode from either format
let decoder = JSONDecoder()
let version = try decoder.decode(OSVer.self, from: jsonData)
let v1 = OSVer(major: 1, minor: 2)
let v2 = OSVer(major: 1, minor: 3)
// Compare versions
if v1 < v2 {
print("Version 1 is older")
}
// Use in collections
let versions: Set<OSVer> = [v1, v2]
let versionMap: [OSVer: String] = [
v1: "Initial Release",
v2: "Feature Update"
]
此库基于 MIT 许可证发布。详情请参阅 LICENSE。