Clamped: A Swift Property Wrapper

Twitter: @cypher_poet

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

Features

  • ✅ 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.

Installation

Xcode Projects

Select File -> Swift Packages -> Add Package Dependency and enter https://github.com/CypherPoet/ClampedPropertyWrapper.

Swift Package Manager Projects

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

let package = Package(
    //...
    dependencies: [
        .package(url: "https://github.com/CypherPoet/ClampedPropertyWrapper", .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: [
    .target(
        name: "YourLibrary",
        dependencies: [
          "ClampedPropertyWrapper",
        ],
        ...
    ),
    ...
]

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

Usage

Basic Example:

import ClampedPropertyWrapper

struct Player {

    @Clamped(
        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

Contributing

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

💻 Developing

Requirements

  • 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.

Description

  • Swift Tools 5.3.0
View More Packages from this Author

Dependencies

  • None
Last updated: Wed Nov 13 2024 03:26:17 GMT-1000 (Hawaii-Aleutian Standard Time)