-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
// | ||
// Comparable+Clip.swift | ||
// BXSwiftUtils | ||
// | ||
// Created by Benjamin Federer on 21.11.18. | ||
// Copyright © 2018 Boinx Software Ltd. & Imagine GbR. All rights reserved. | ||
// | ||
|
||
import Foundation | ||
|
||
extension Comparable | ||
{ | ||
/// Returns `self` clipped to the closed interval `[minValue, maxValue]`. | ||
/// | ||
/// - Parameters: | ||
/// - minValue: The minimum allowed value. Will clip `self` if smaller. | ||
/// - maxValue: The maximum allowed value. Will clip `self` if greater. | ||
/// - Returns: `self` if `self` is within the interval `[minValue, maxValue]`, `minValue` or `maxValue` otherwise. | ||
public func clipped<T>(minValue: T, maxValue: T) -> T where T : Comparable | ||
{ | ||
return min(maxValue, max(minValue, self as! T)) | ||
} | ||
|
||
/// Clips to the closed interval `[minValue, maxValue]`. | ||
/// | ||
/// - Parameters: | ||
/// - minValue: The minimum allowed value. Will clip `self` if smaller. | ||
/// - maxValue: The maximum allowed value. Will clip `self` if greater. | ||
public mutating func clip<T>(minValue: T, maxValue: T) where T : Comparable | ||
{ | ||
self = min(maxValue, max(minValue, self as! T)) as! Self | ||
} | ||
} |