Skip to content

Instantly share code, notes, and snippets.

@KyLeggiero
Created November 6, 2017 20:20
Show Gist options
  • Save KyLeggiero/5bbd4f0b9cf0fc55dc62be6296b266d1 to your computer and use it in GitHub Desktop.
Save KyLeggiero/5bbd4f0b9cf0fc55dc62be6296b266d1 to your computer and use it in GitHub Desktop.
A proof-of-concept that attempts to create a syntax like "left < center < right", which ensures that "center" is both greater than "left" and less than "right".
//
// Swift range conformance check.swift
// Requires Swift 4
//
// Created by Ben Leggiero on 2017-11-06.
// Copyright © 2017 Ben Leggiero using BH-1-PS license
//
// This is a proof-of-concept that attempts to create a syntax like "left < center < right", which ensures that
// "center" is both greater than "left" and less than "right".
//
// This was created to address the idea put forth by Sid Mani in this SwifterSwift GitHub issue:
// https://github.com/SwifterSwift/SwifterSwift/issues/274
//
infix operator <: AdditionPrecedence
public struct PartialComparison_LeftAndCenter<T : Comparable> {
// In case you want to save the original left side for later, uncomment this line:
//let left: T
let center: T
let leftIsLessThanCenter: Bool
init(left: T, center: T) {
// In case you want to save the orignal left side for later, uncomment this line:
//self.left = left
self.center = center
self.leftIsLessThanCenter = left < center
}
public static func <(partialLeft: PartialComparison_LeftAndCenter<T>, right: T) -> Bool {
return partialLeft.leftIsLessThanCenter && partialLeft.center < right
}
}
public extension Comparable {
fileprivate func isLowerBound_creatingPartialLeftSide(of center: Self) -> PartialComparison_LeftAndCenter<Self> {
return PartialComparison_LeftAndCenter(left: self, center: center)
}
public static func <(lowerBound: Self, center: Self) -> PartialComparison_LeftAndCenter<Self> {
return lowerBound.isLowerBound_creatingPartialLeftSide(of: center)
}
}
assert((1 < 2 < 3) == true, "1 < 2 < 3 == true")
assert((3 < 2 < 1) == false, "3 < 2 < 1 == false")
assert((1 < 1 < 3) == false, "1 < 1 < 3 == false")
assert((1 < 3 < 3) == false, "1 < 3 < 3 == false")
assert((1 < 1.5 < 2) == true, "1 < 1.5 < 3 == true")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment