I do have an actual use case, but I think it's a little harder to explain:
It involves an Interval
type I built to model mathematical intervals. The type has operators for creating all kinds of intervals, except for the unbounded ones.
For example, 5≤∙∙
creates an interval that's left-closed and -bounded at 5
and right-open and -unbounded; ∙∙≤10
creates an interval that's left-open and -unbounded and right-closed and -bounded at 10
. Interval<Int>.unbounded
creates an unbounded interval of integers.
In the use case I linked above, the program is a mod manager for a game, and it reads some version strings from a JSON object in order to figure out dependencies between mods. The dependency could be either an exact version number, or a combination of minimum or maximum versions. The version information could be absent, in which case any version is acceptable.
I modeled all the different versions like this: [exact version, exact version], [minimum version, +∞), (-∞, maximum version], [minimum version, maximum version], (-∞, +∞). If either minimum version or maximum version is absent (nil
), then it is assumed to be unbounded. In code, it becomes:
let minimalVersion = try container.decodeIfPresent(CKANMetadataVersion.self, forKey: .minimalVersion)
let lowerBoundedVersions = minimalVersion?≤∙∙ ?? .unbounded
let maximalVersion = try container.decodeIfPresent(CKANMetadataVersion.self, forKey: .maximalVersion)
let upperBoundedVersions = ∙∙≤maximalVersion? ?? .unbounded // Optional chaining doesn't work here.
let versions = lowerBoundedVersions ∩ upperBoundedVersions
^ line 4 doesn't work because prefix operators can't be optional chained, so it's written as this instead:
var upperBoundedVersions = Interval<CKANMetadataVersion>.unbounded
if let maximalVersion = try container.decodeIfPresent(CKANMetadataVersion.self, forKey: .maximalVersion) {
upperBoundedVersions = ∙∙≤maximalVersion
}