Skip to content

Instantly share code, notes, and snippets.

@maakcode
Created September 6, 2021 21:25
Show Gist options
  • Save maakcode/96146dee4dcfa10e4cec23f05be673fa to your computer and use it in GitHub Desktop.
Save maakcode/96146dee4dcfa10e4cec23f05be673fa to your computer and use it in GitHub Desktop.
Clamped with Range extension in Swift
import UIKit
import XCTest
import PlaygroundSupport
extension Int {
func clamped(_ range: Range<Self>) -> Self {
if range.contains(self) {
return self
}
return self < range.lowerBound ? range.lowerBound : range.upperBound - 1
}
}
extension Numeric where Self: Comparable {
func clamped(_ range: ClosedRange<Self>) -> Self {
if range.contains(self) {
return self
}
return self < range.lowerBound ? range.lowerBound : range.upperBound
}
}
class ClampedTest: XCTestCase {
func testIntClosedRange() {
XCTAssertEqual(0.clamped(1...10), 1)
XCTAssertEqual(5.clamped(1...10), 5)
XCTAssertEqual(15.clamped(1...10), 10)
}
func testIntRange() {
XCTAssertEqual(0.clamped(1..<10), 1)
XCTAssertEqual(5.clamped(1..<10), 5)
XCTAssertEqual(15.clamped(1..<10), 9)
}
func testFloatClosedRange() {
XCTAssertEqual(Float(0).clamped(1.1...11.1), 1.1)
XCTAssertEqual(Float(5).clamped(1.1...11.1), 5)
XCTAssertEqual(Float(15).clamped(1.1...11.1), 11.1)
}
func testCGFloatClosedRange() {
XCTAssertEqual(CGFloat(0).clamped(1.1...11.1), 1.1)
XCTAssertEqual(CGFloat(5).clamped(1.1...11.1), 5)
XCTAssertEqual(CGFloat(15).clamped(1.1...11.1), 11.1)
}
}
ClampedTest.defaultTestSuite.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment