|
| 1 | +# Swift Rational |
| 2 | + |
| 3 | +## Introduction |
| 4 | + |
| 5 | +Swift Numerics provides the `RationalModule` module for working with rational numbers in Swift. |
| 6 | +```swift |
| 7 | +import RationalModule |
| 8 | + |
| 9 | +let half = Rational<Int>(1, 2) |
| 10 | +``` |
| 11 | + |
| 12 | +`RationalModule` has only a single dependency, [swift-numerics](https://github.com/apple/swift-numerics/tree/main). |
| 13 | + |
| 14 | +## Using Swift Rational in your project |
| 15 | + |
| 16 | +To use Swift Rational in a SwiftPM project: |
| 17 | + |
| 18 | +1. Add the following line to the dependencies in your `Package.swift` file: |
| 19 | + |
| 20 | +```swift |
| 21 | +.package(url: "https://github.com/abdel-17/swift-rational", from: "1.0.0") |
| 22 | +``` |
| 23 | + |
| 24 | +2. Add `RationalModule` as a dependency for your target: |
| 25 | + |
| 26 | +```swift |
| 27 | +.target( |
| 28 | + name: "TargetName", |
| 29 | + dependencies: [ |
| 30 | + .product(name: "RationalModule", package: "swift-rational") |
| 31 | + ] |
| 32 | +) |
| 33 | +``` |
| 34 | + |
| 35 | +3. Add `import RationalModule` in your source code. |
| 36 | + |
| 37 | +## API |
| 38 | + |
| 39 | +`RationalModule` exports the `Rational` struct. It conforms to standard Swift protocols like `AdditiveArithmetic`, `Numeric`, `Hashable`, `Comparable`, and more. |
| 40 | + |
| 41 | +You can create a `Rational` value using the fraction initializer. |
| 42 | +```swift |
| 43 | +let half = Rational(2, 4) |
| 44 | +print(x.numerator) // 1 |
| 45 | +print(x.denominator) // 2 |
| 46 | +``` |
| 47 | + |
| 48 | +You can also use the integer initializer. |
| 49 | +```swift |
| 50 | +let one = Rational(1) |
| 51 | +``` |
| 52 | + |
| 53 | +Or simply an integer literal. |
| 54 | +```swift |
| 55 | +let two: Rational<Int> = 2 |
| 56 | +``` |
| 57 | + |
| 58 | +`Rational` supports the standard arithmetic and comparison operators. |
| 59 | +```swift |
| 60 | +Rational(1, 2) + Rational(1, 4) // Rational(3, 4) |
| 61 | +Rational(1) - Rational(1, 2) // Rational(1, 2) |
| 62 | +Rational(2) * Rational(3, 4) // Rational(3, 2) |
| 63 | +Rational(1) / Rational(1, 2) // Rational(2, 1) |
| 64 | +Rational(1, 2) < Rational(3, 4) // true |
| 65 | +``` |
0 commit comments