From 0962ae290044d24722610234cb215b748722f196 Mon Sep 17 00:00:00 2001 From: cdricms <36056008+cdricms@users.noreply.github.com> Date: Tue, 2 Sep 2025 21:09:42 +0200 Subject: [PATCH] Energy units --- Sources/Units/Units.swift | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Sources/Units/Units.swift b/Sources/Units/Units.swift index 15e7e55..406ab32 100644 --- a/Sources/Units/Units.swift +++ b/Sources/Units/Units.swift @@ -33,6 +33,7 @@ public enum UnitCategory: String, CaseIterable, CustomStringConvertible, case time case temperature case speed + case energy // Add more categories as needed public var description: String { @@ -102,6 +103,11 @@ public enum Unit: String, CaseIterable, CustomStringConvertible, Codable, case milesPerHour = "mph" case knots = "kn" + // MARK: Energy units + case joule = "J" + case kilocalorie = "kcal" + case kilojoule = "kJ" + public var category: UnitCategory { switch self { case .kilogram, .gram, .milligram, .microgram, .pound, .ounce, @@ -119,6 +125,8 @@ public enum Unit: String, CaseIterable, CustomStringConvertible, Codable, case .celsius, .fahrenheit, .kelvin: return .temperature case .metersPerSecond, .kilometersPerHour, .milesPerHour, .knots: return .speed + case .kilocalorie, .kilojoule, .joule: + return .energy } } @@ -173,6 +181,12 @@ public enum Unit: String, CaseIterable, CustomStringConvertible, Codable, case .kilometersPerHour: 1000.0 / 3600.0 case .milesPerHour: 1609.344 / 3600.0 case .knots: 0.514444 + + // Energy (Base: Joule) + case .joule: 1.0 + case .kilojoule: 1000.0 + case .kilocalorie: 4184.0 + } } @@ -420,6 +434,7 @@ extension UnitCategory { case .time: return .second case .temperature: return .celsius case .speed: return .metersPerSecond + case .energy: return .joule } } } @@ -484,6 +499,11 @@ extension ConvertibleToDouble { public var mph: UnitValue { .init(value: self, unit: .milesPerHour) } public var kn: UnitValue { .init(value: self, unit: .knots) } + // MARK: Energy Initializers + public var J: UnitValue { .init(value: self, unit: .joule) } + public var kJ: UnitValue { .init(value: self, unit: .kilojoule) } + public var kcal: UnitValue { .init(value: self, unit: .kilocalorie) } + // MARK: - Subscripts for Numeric /// Allows creating a UnitValue directly from a numeric literal using a Unit enum case. /// Example: `10[.kg]` @@ -557,6 +577,12 @@ extension UnitValue where ValueType: ConvertibleToDouble { // Apply constraints public var kmh: UnitValue? { converted(to: .kilometersPerHour) } public var mph: UnitValue? { converted(to: .milesPerHour) } public var kn: UnitValue? { converted(to: .knots) } + + // MARK: Energy Conversions + public var J: UnitValue? { converted(to: .joule) } + public var kJ: UnitValue? { converted(to: .kilojoule) } + public var kcal: UnitValue? { converted(to: .kilocalorie) } + } // MARK: - Height Conversion Extensions