.clamped(in:)
๐พ ็จๅผ๏ผ paiza.io
// 2022.02.13 + (method) .clamped(in: 5...), .clamped(in: ...8)
// ๐ Comparable + .clamped(in:)
extension Comparable {
/// โญ๏ธ clamp a `Comparable` in a `ClosedRange` (lowerBound...upperBound).
/// ```
/// 3.clamped(in: 5...8) // 5
/// 6.clamped(in: 5...8) // 6
/// 9.clamped(in: 5...8) // 8
/// ```
public func clamped(in range: ClosedRange<Self>) -> Self {
min(max(self, range.lowerBound), range.upperBound)
}
/// โญ๏ธ clamp a `Comparable` in a `PartialRangeFrom` (lowerBound...).
/// ```
/// 3.clamped(in: 5...) // 5
/// 6.clamped(in: 5...) // 6
/// 9.clamped(in: 5...) // 9
/// Int.min.clamped(in: 5...) // 5
/// Int.max.clamped(in: 5...) // 9223372036854775807
/// ```
public func clamped(in range: PartialRangeFrom<Self>) -> Self {
range.contains(self) ? self : range.lowerBound
}
/// โญ๏ธ clamp a `Comparable` in a `PartialRangeThrough` (...upperBound).
/// ```
/// 3.clamped(in: ...8) // 3
/// 6.clamped(in: ...8) // 6
/// 9.clamped(in: ...8) // 8
/// Int.min.clamped(in: ...8) // -9223372036854775808
/// Int.max.clamped(in: ...8) // 8
/// ```
public func clamped(in range: PartialRangeThrough<Self>) -> Self {
range.contains(self) ? self : range.upperBound
}
}
// test
func test_clamped() {
[
// test `ClosedRange``
3.clamped(in: 5...8), // 5
6.clamped(in: 5...8), // 6
9.clamped(in: 5...8), // 8
// test `PartialRangeFrom` (min...)
3.clamped(in: 5...), // 5
6.clamped(in: 5...), // 6
9.clamped(in: 5...), // 9
Int.min.clamped(in: 5...), // 5
Int.max.clamped(in: 5...), // 9223372036854775807
// test `PartialRangeFrom` (min...)
3.clamped(in: ...8), // 3
6.clamped(in: ...8), // 6
9.clamped(in: ...8), // 8
Int.min.clamped(in: ...8), // -9223372036854775808
Int.max.clamped(in: ...8), // 8
].forEach { print($0) }
}
Swift โฉ
Collections โฉ Supporting Types โฉ
PartialRangeFrom<Bound: Comparable> (struct) - (SwiftDoc)
PartialRangeThrough<Bound: Comparable> (struct) - (SwiftDoc)
TestFrameView - used to constrain child view's width.
History
2022.02.13
// ๐ Comparable + clamp
extension Comparable {
// comparable.clamped(in: range)
public func clamped(in range: ClosedRange<Self>) -> Self {
min(max(self, range.lowerBound), range.upperBound)
}
}
Last updated