Clamped: A Swift Property Wrapper

Twitter: @cypher_poet

A Swift Property Wrapper for automatically clamping Comparable values to closed or partial ranges.


  • ✅ Clamp any Comparable type to a ClosedRange or a "Half-Open" range.
  • ✅ Additional support for initializing clamped FloatingPoint properties with a PartialRangeThrough, PartialRangeFrom, or PartialRangeUpTo expression.
  • ✅ Initialize clamped FloatingPoint or FixedWidthInteger properties with exclusive lower and upper bounds.


Xcode Projects

Select File -> Swift Packages -> Add Package Dependency and enter

Swift Package Manager Projects

You can add ClampedPropertyWrapper as a package dependency in your Package.swift file:

let package = Package(
    dependencies: [
        .package(url: "", .upToNextMinor(from: "0.2.0")),

From there, refer to ClampedPropertyWrapper as a "target dependency" in any of your package's targets that need it.

targets: [
        name: "YourLibrary",
        dependencies: [

Then simply import ClampedPropertyWrapper wherever you’d like to use it.


Basic Example:

import ClampedPropertyWrapper

struct Player {

        above: 0.0.nextDown,
        andBelow: .infinity
    var xp: Double = 0.0

    @Clamped(to: 1..<100)
    var level: Int = 1

    @Clamped(above: 0.0, andBelow: Double.infinity)
    var number: Double = 1.0

    @Clamped(to: "A"..."Z")
    var firstInitial: Character = "A"

    @Clamped(to: 0.0...)
    var ammo: Double = 0.1

    @Clamped(to: ...100.0)
    var reputation: Double = .zero

    @Clamped(to: ..<20)
    var weeklyLeaderboardRankChange: Int = .zero

You can also take things further in this project's Xcode Playground:

Playground Example


Contributions to ClampedPropertyWrapper are most welcome. Check out some of the issue templates for more info.

💻 Developing


  • Xcode 12.5+ (Recommended)

📜 Generating Documentation

Documentation is generated by Swift Doc. Installation instructions can be found here, and as soon as you have it set up, docs can be generated simply by running ./Scripts/generate-html-docs.zsh from the command line.

📝 Note that this will only generate a .build/documentation folder for you to view locally. This folder is being ignored by git, and a GitHub action exists to automatically generate docs at the root level and serve them on the project's gh-pages branch.

🏷 License

ClampedPropertyWrapper is available under the MIT license. See the LICENSE file for more info.


  • Swift Tools 5.3.0
View More Packages from this Author


  • None
Last updated: Tue Nov 29 2022 09:48:14 GMT-0500 (GMT-05:00)