### Use Generator Combinators Source: https://github.com/typelift/swiftcheck/blob/master/README.md Examples of using built-in combinators to create custom generators for various data types. ```swift let onlyEven = Int.arbitrary.suchThat { $0 % 2 == 0 } let vowels = Gen.fromElements(of: [ "A", "E", "I", "O", "U" ]) let randomHexValue = Gen.choose((0, 15)) let uppers = Gen.fromElements(in: "A"..."Z") let lowers = Gen.fromElements(in: "a"..."z") let numbers = Gen.fromElements(in: "0"..."9") /// This generator will generate `.none` 1/4 of the time and an arbitrary /// `.some` 3/4 of the time let weightedOptionals = Gen.frequency([ (1, Gen.pure(nil)), (3, Int.arbitrary.map(Optional.some)) ]) ``` -------------------------------- ### Swift XCTest Integration: Standard Property Source: https://context7.com/typelift/swiftcheck/llms.txt Integrates SwiftCheck properties into XCTest methods. This example tests the concatenation length of strings. Requires SwiftCheck and XCTest imports. ```swift import SwiftCheck import XCTest class StringSpec: XCTestCase { func testStringProperties() { // Standard property notation property("Concatenation length") <- forAll { (s1: String, s2: String) in return (s1 + s2).count == s1.count + s2.count } // Multiple properties in one test method property("Empty string identity") <- forAll { (s: String) in return s + "" == s && "" + s == s } property("String reversal") <- forAll { (s: String) in return String(s.reversed().reversed()) == s } } // ... other test methods } ``` -------------------------------- ### Custom Arbitrary Protocol Conformance for Config Struct Source: https://context7.com/typelift/swiftcheck/llms.txt Demonstrates using Gen.compose for cleaner initialization of arbitrary Config instances. ```swift public struct Config: Arbitrary { var timeout: Int var retryCount: Int var debugMode: Bool public static var arbitrary: Gen { return Gen.compose { composer in var config = Config(timeout: 0, retryCount: 0, debugMode: false) config.timeout = composer.generate() config.retryCount = composer.generate(using: Gen.choose((0, 5))) config.debugMode = composer.generate() return config } } } ``` -------------------------------- ### Custom Arbitrary Protocol Conformance for User Struct Source: https://context7.com/typelift/swiftcheck/llms.txt Defines how to generate arbitrary User instances for testing. Includes shrinking logic for better counterexamples. ```swift import SwiftCheck // Custom struct with Arbitrary conformance public struct User { let id: Int let name: String let isActive: Bool } extension User: Arbitrary { public static var arbitrary: Gen { return Gen<(Int, String, Bool)>.zip( Int.arbitrary, String.arbitrary, Bool.arbitrary ).map { User(id: $0.0, name: $0.1, isActive: $0.2) } } // Optional: Define shrinking for better counterexamples public static func shrink(_ user: User) -> [User] { // Shrink by trying simpler names and IDs return Int.shrink(user.id).map { User(id: $0, name: user.name, isActive: user.isActive) } + String.shrink(user.name).map { User(id: user.id, name: $0, isActive: user.isActive) } } } ``` -------------------------------- ### Define a basic property test Source: https://github.com/typelift/swiftcheck/blob/master/README.md Use the property function and forAll quantifier to verify that a property holds for a given type. ```swift func testAll() { // 'property' notation allows us to name our tests. This becomes important // when they fail and SwiftCheck reports it in the console. property("Integer Equality is Reflexive") <- forAll { (i : Int) in return i == i } } ``` -------------------------------- ### Generate Initial Segments with Gen.fromInitialSegments Source: https://context7.com/typelift/swiftcheck/llms.txt Use `Gen<[T]>.fromInitialSegments(of:)` to generate prefixes (initial segments) of a given array. The length of the generated segment typically grows with the test size. ```swift import SwiftCheck // Initial segments of an array (grows with test size) let segments = Gen<[Int]>.fromInitialSegments(of: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) property("Segments are prefixes") <- forAllNoShrink(segments) { seg in return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].prefix(seg.count) == ArraySlice(seg) } ``` -------------------------------- ### Swift Property Test with Automatic Shrinking Source: https://context7.com/typelift/swiftcheck/llms.txt Demonstrates a property test that fails and triggers SwiftCheck's automatic shrinking to find the minimal counterexample. Requires SwiftCheck import. ```swift import SwiftCheck // Buggy sieve implementation (fails for n=4) func sieve(_ n: Int) -> [Int] { guard n > 1 else { return [] } var marked = [Bool](repeating: false, count: n + 1) marked[0] = true marked[1] = true for p in 2.. Bool { guard n > 1 else { return false } guard n > 2 else { return true } let max = Int(ceil(sqrt(Double(n)))) for i in 2...max { if n % i == 0 { return false } } return true } // This test will fail and shrink to minimal counterexample: 4 property("Sieve generates only primes") <- forAll { (n: Positive) in let value = n.getPositive return sieve(value).allSatisfy(isPrime) } ``` -------------------------------- ### Define properties with preconditions Source: https://github.com/typelift/swiftcheck/blob/master/README.md Use the implication operator ==> to define preconditions; tests are discarded if the precondition fails. ```swift property("Shrunken lists of integers always contain [] or [0]") <- forAll { (l : [Int]) in // Here we use the Implication Operator `==>` to define a precondition for // this test. If the precondition fails the test is discarded. If it holds // the test proceeds. return (!l.isEmpty && l != [0]) ==> { let ls = self.shrinkArbitrary(l) return (ls.filter({ $0 == [] || $0 == [0] }).count >= 1) } } ``` -------------------------------- ### Compose properties with conjunction and labels Source: https://github.com/typelift/swiftcheck/blob/master/README.md Combine multiple sub-properties using the ^&&^ operator and label them with for detailed failure reporting. ```swift property("The reverse of the reverse of an array is that array") <- forAll { (xs : [Int]) in // This property is using a number of SwiftCheck's more interesting // features. `^&&^` is the conjunction operator for properties that turns // both properties into a larger property that only holds when both sub-properties // hold. `` is the labelling operator allowing us to name each sub-part // in output generated by SwiftCheck. For example, this property reports: // // *** Passed 100 tests // (100% , Right identity, Left identity) return (xs.reversed().reversed() == xs) "Left identity" ^&&^ (xs == xs.reversed().reversed()) "Right identity" } ``` -------------------------------- ### Compose Generators with Gen.compose Source: https://github.com/typelift/swiftcheck/blob/master/README.md Use Gen.compose to procedurally construct instances of a type from multiple generators. ```swift public static var arbitrary : Gen { return Gen.compose { c in return MyClass( // Use the nullary method to get an `arbitrary` value. a: c.generate(), // or pass a custom generator b: c.generate(Bool.suchThat { $0 == false }), // .. and so on, for as many values and types as you need. c: c.generate(), ... ) } } ``` -------------------------------- ### Define properties with forAll Source: https://context7.com/typelift/swiftcheck/llms.txt Use the property function combined with forAll to define testable invariants. SwiftCheck automatically runs 100 test cases by default. ```swift import SwiftCheck import XCTest class MathSpec: XCTestCase { func testProperties() { // Basic property test with single parameter property("Integer addition is commutative") <- forAll { (a: Int, b: Int) in return a + b == b + a } // Property with multiple parameters (up to 8 supported) property("Array concatenation length") <- forAll { (xs: [Int], ys: [Int]) in return (xs + ys).count == xs.count + ys.count } // Property returning Bool is automatically testable property("String equality is reflexive") <- forAll { (s: String) in return s == s } } } // Output on success: // *** Passed 100 tests // . ``` -------------------------------- ### Custom Shrinking Logic with forAllShrink Source: https://context7.com/typelift/swiftcheck/llms.txt Provide a custom shrinking function to `forAllShrink` to control how generated values are reduced when a test fails. This is useful for types that require specific shrinking strategies. ```swift import SwiftCheck // forAllShrink with custom shrinker func shrinkPositive(_ n: Int) -> [Int] { guard n > 1 else { return [] } return [n / 2, n - 1].filter { $0 > 0 } } property("With custom shrink") <- forAllShrink(smallPositive, shrinker: shrinkPositive) { n in return n > 0 } ``` -------------------------------- ### SwiftCheck quickCheck Function with Arguments Source: https://context7.com/typelift/swiftcheck/llms.txt Directly uses the quickCheck function to run a property test with custom arguments, asserting the property and providing a descriptive label. ```swift import SwiftCheck // Using quickCheck function directly quickCheck(asserting: "Addition commutes", arguments: thoroughArgs) { forAll { (a: Int, b: Int) in return a + b == b + a } } ``` -------------------------------- ### Generate Specific Elements with Gen.fromElements Source: https://context7.com/typelift/swiftcheck/llms.txt Use `Gen.fromElements(of:)` to create a generator that randomly picks values from a predefined set. Combine with `forAllNoShrink` when the type does not have a default Arbitrary instance or shrinking is not desired. ```swift import SwiftCheck // forAllNoShrink skips shrinking (useful for non-Arbitrary types) let customGen = Gen.fromElements(of: ["alpha", "beta", "gamma"]) property("Custom strings") <- forAllNoShrink(customGen) { s in return ["alpha", "beta", "gamma"].contains(s) } ``` -------------------------------- ### SwiftCheck CheckerArguments for Replaying Test Cases Source: https://context7.com/typelift/swiftcheck/llms.txt Sets up custom arguments to replay a specific failing test case using a provided seed and size, ensuring reproducibility of failures. ```swift import SwiftCheck // Replay a specific failing test case let replayArgs = CheckerArguments( replay: (StdGen(1234, 5678), 50) // Seed and size from failure output ) property("Replay test", arguments: replayArgs) <- forAll { (x: Int) in return x >= 0 // Will replay the exact same test case } ``` -------------------------------- ### Patch Sieve Implementation Source: https://github.com/typelift/swiftcheck/blob/master/README.md A diff showing the correction of a sieve loop range. ```diff - for i in stride(from: 2 * p, to: n, by: p) { + for i in stride(from: 2 * p, through: n, by: p) { ``` -------------------------------- ### Generate Non-Zero Values with NonZero Source: https://context7.com/typelift/swiftcheck/llms.txt Use `NonZero` to generate any value except zero. This is crucial for operations that would fail or behave unexpectedly with zero as an input, like division. ```swift import SwiftCheck // NonZero generates any non-zero value property("Division by non-zero succeeds") <- forAll { (a: Int, b: NonZero) in let divisor = b.getNonZero return (a / divisor) * divisor + (a % divisor) == a } ``` -------------------------------- ### Define Custom Integer and Double Generators Source: https://context7.com/typelift/swiftcheck/llms.txt Create custom generators for specific ranges using `Gen.choose()`. This provides fine-grained control over the values used in tests. ```swift import SwiftCheck // Custom generator for specific test scenarios let smallPositive = Gen.choose((1, 100)) let percentage = Gen.choose((0.0, 1.0)) property("Custom ranges") <- forAll(smallPositive, percentage) { (count, pct) in return count > 0 && pct >= 0.0 && pct <= 1.0 } ``` -------------------------------- ### Generate Permutations with Gen.fromShufflingElements Source: https://context7.com/typelift/swiftcheck/llms.txt Use `Gen<[T]>.fromShufflingElements(of:)` to create a generator that produces random permutations of a given array. This is useful for testing algorithms that should be invariant to element order. ```swift import SwiftCheck // Generate permutations of an array let shuffled = Gen<[Int]>.fromShufflingElements(of: [1, 2, 3, 4, 5]) property("Permutations have same elements") <- forAllNoShrink(shuffled) { arr in return Set(arr) == Set([1, 2, 3, 4, 5]) } ``` -------------------------------- ### Swift XCTest Integration: Coverage Requirements Source: https://context7.com/typelift/swiftcheck/llms.txt Ensures sufficient coverage of different cases within a SwiftCheck property test using the `cover` function. Requires SwiftCheck and XCTest imports. ```swift import SwiftCheck import XCTest class StringSpec: XCTestCase { // ... other test methods func testCoverageRequirements() { // Ensure sufficient coverage of different cases property("Coverage test") <- forAll { (n: Int) in return (n > 0).cover(n > 0, percentage: 30, label: "positive") && (n < 0).cover(n < 0, percentage: 30, label: "negative") && (n == 0).cover(n == 0, percentage: 1, label: "zero") } } } ``` -------------------------------- ### Implement Arbitrary Protocol for Custom Types Source: https://github.com/typelift/swiftcheck/blob/master/README.md Conform custom types to the Arbitrary protocol to enable random generation in SwiftCheck tests. ```swift import SwiftCheck public struct ArbitraryFoo { let x : Int let y : Int public var description : String { return "Arbitrary Foo!" } } extension ArbitraryFoo : Arbitrary { public static var arbitrary : Gen { return Gen<(Int, Int)>.zip(Int.arbitrary, Int.arbitrary).map(ArbitraryFoo.init) } } class SimpleSpec : XCTestCase { func testAll() { property("ArbitraryFoo Properties are Reflexive") <- forAll { (i : ArbitraryFoo) in return i.x == i.x && i.y == i.y } } } ``` -------------------------------- ### Generate Mutable Custom Types Source: https://github.com/typelift/swiftcheck/blob/master/README.md Demonstrates using Gen.compose to initialize and mutate a struct during generation. ```swift public struct ArbitraryMutableFoo : Arbitrary { var a: Int8 var b: Int16 public init() { a = 0 b = 0 } public static var arbitrary: Gen { return Gen.compose { c in var foo = ArbitraryMutableFoo() foo.a = c.generate() foo.b = c.generate() return foo } } } ``` -------------------------------- ### Add SwiftCheck Dependency Source: https://github.com/typelift/swiftcheck/blob/master/README.md Configuration for adding SwiftCheck to a Swift Package Manager project. ```swift .package(url: "https://github.com/typelift/SwiftCheck.git", from: "0.8.1") ``` -------------------------------- ### Implement Sieve of Eratosthenes Source: https://github.com/typelift/swiftcheck/blob/master/README.md A function to generate prime numbers up to n, used here to demonstrate code that can be subjected to property testing. ```swift /// The Sieve of Eratosthenes: /// /// To find all the prime numbers less than or equal to a given integer n: /// - let l = [2...n] /// - let p = 2 /// - for i in [(2 * p) through n by p] { /// mark l[i] /// } /// - Remaining indices of unmarked numbers are primes func sieve(_ n : Int) -> [Int] { if n <= 1 { return [] } var marked : [Bool] = (0...n).map { _ in false } marked[0] = true marked[1] = true for p in 2..= 0 } } // ... other test methods } ``` -------------------------------- ### Check Primality in Swift Source: https://github.com/typelift/swiftcheck/blob/master/README.md A helper function to determine if an integer is prime by checking for a nonzero modulus. ```swift func isPrime(n : Int) -> Bool { if n == 0 || n == 1 { return false } else if n == 2 { return true } let max = Int(ceil(sqrt(Double(n)))) for i in 2...max { if n % i == 0 { return false } } return true } ``` -------------------------------- ### Swift Property Test for Existential Quantification (Exists) Source: https://context7.com/typelift/swiftcheck/llms.txt Tests if at least one generated integer satisfies the condition of being even. Requires SwiftCheck import. ```swift import SwiftCheck // Test that there exists an even number property("Some integers are even") <- exists { (n: Int) in return n % 2 == 0 } ``` -------------------------------- ### SwiftCheck Labels () for Property Identification Source: https://context7.com/typelift/swiftcheck/llms.txt Applies labels to different parts of a property using the '' operator, which helps in identifying the specific condition that failed during testing. ```swift import SwiftCheck // Labels () help identify which part of a property failed property("Set operations") <- forAll { (xs: Set, ys: Set) in return (xs.union(ys).count >= xs.count) "Union is at least as large" ^&&^ (xs.intersection(ys).count <= xs.count) "Intersection is at most as large" } ``` -------------------------------- ### Generate Positive Integers with Positive Source: https://context7.com/typelift/swiftcheck/llms.txt Use `Positive` to generate values strictly greater than zero. This is useful for properties that require positive inputs, such as mathematical operations. ```swift import SwiftCheck // Positive generates only positive numbers (> 0) property("Square root of positive is real") <- forAll { (n: Positive) in let value = n.getPositive return value > 0 } ``` -------------------------------- ### Generate random values with Gen Source: https://context7.com/typelift/swiftcheck/llms.txt The Gen type provides combinators for creating, transforming, and constraining random data generators. ```swift import SwiftCheck // Generate random integers in a specific range let diceRoll = Gen.choose((1, 6)) print(diceRoll.generate) // Random value 1-6 // Select from a collection of elements let vowels = Gen.fromElements(of: ["A", "E", "I", "O", "U"]) print(vowels.generate) // Random vowel // Generate from a closed range let lowercase = Gen.fromElements(in: "a"..."z") // Filter generated values with suchThat let evenNumbers = Int.arbitrary.suchThat { $0 % 2 == 0 } // Generate arrays with proliferate let intArrays = Int.arbitrary.proliferate // Gen<[Int]> let nonEmptyArrays = Int.arbitrary.proliferateNonEmpty // Gen<[Int]> (never empty) let fixedSizeArray = Int.arbitrary.proliferate(withSize: 5) // Always 5 elements // Transform generators with map let positiveDoubles = Int.arbitrary.map { abs(Double($0)) } // Chain generators with flatMap let randomLengthString = Gen.choose((1, 10)).flatMap { length in Character.arbitrary.proliferate(withSize: length).map { String($0) } } // Weighted selection with frequency let weightedBools = Gen.frequency([ (3, Gen.pure(true)), // 75% chance (1, Gen.pure(false)) // 25% chance ]) // Select one generator randomly from multiple let mixedNumbers = Gen.one(of: [ Gen.choose((0, 10)), Gen.choose((100, 200)), Gen.choose((-50, -1)) ]) // Resize generator for larger/smaller values let largerInts = Int.arbitrary.resize(1000) ``` -------------------------------- ### Define a SwiftCheck Property Source: https://github.com/typelift/swiftcheck/blob/master/README.md Use the property function to verify that a sieve implementation correctly identifies prime numbers. ```swift import SwiftCheck property("All Prime") <- forAll { (n : Int) in return sieve(n).filter(isPrime) == sieve(n) } ``` -------------------------------- ### SwiftCheck CheckerArguments for Thorough Testing Source: https://context7.com/typelift/swiftcheck/llms.txt Configures custom arguments for thorough testing, increasing the maximum number of successful tests and discarded tests, and the maximum test case size. ```swift import SwiftCheck // Custom arguments for more thorough testing let thoroughArgs = CheckerArguments( maxAllowableSuccessfulTests: 500, // Run 500 tests instead of 100 maxAllowableDiscardedTests: 1000, // Allow more discards maxTestCaseSize: 200 // Generate larger values ) property("Thorough array test", arguments: thoroughArgs) <- forAll { (xs: [Int]) in return xs.reversed().reversed() == xs } ``` -------------------------------- ### SwiftCheck Conjunction Operator (^&&^) Source: https://context7.com/typelift/swiftcheck/llms.txt Combines multiple properties using the conjunction operator, requiring all to hold true for the test to pass. Includes labels for easier failure identification. ```swift import SwiftCheck // Conjunction (^&&^) requires both properties to hold property("Array reverse properties") <- forAll { (xs: [Int]) in return (xs.reversed().reversed() == xs) "Double reverse is identity" ^&&^ (xs.first == xs.reversed().last) "First equals reversed last" } ``` -------------------------------- ### Custom Shrinking Logic for Domain Types Source: https://context7.com/typelift/swiftcheck/llms.txt Defines custom shrinking behavior for a `Range` struct by implementing the `Arbitrary` protocol. This allows SwiftCheck to generate smaller or modified `Range` values when a property fails. ```swift struct Range { let start: Int let end: Int } extension Range: Arbitrary { static var arbitrary: Gen { return Gen<(Int, Int)>.zip(Int.arbitrary, Int.arbitrary) .map { Range(start: min($0.0, $0.1), end: max($0.0, $0.1)) } } static func shrink(_ r: Range) -> [Range] { // Try smaller ranges var results = [Range]() if r.end - r.start > 0 { results.append(Range(start: r.start, end: r.start + (r.end - r.start) / 2)) results.append(Range(start: r.start + (r.end - r.start) / 2, end: r.end)) } // Try shrinking endpoints toward 0 for s in Int.shrink(r.start) { if s <= r.end { results.append(Range(start: s, end: r.end)) } } for e in Int.shrink(r.end) { if e >= r.start { results.append(Range(start: r.start, end: e)) } } return results } } ``` -------------------------------- ### Existential Test with Custom Generator Source: https://context7.com/typelift/swiftcheck/llms.txt Tests if there exists a perfect square within a custom range of positive integers (1 to 1000). Requires SwiftCheck import. ```swift import SwiftCheck // Existential with custom generator let positives = Gen.choose((1, 1000)) property("There exists a perfect square") <- exists(positives) { n in let root = Int(sqrt(Double(n))) return root * root == n } ``` -------------------------------- ### Generate Functions with ArrowOf Source: https://context7.com/typelift/swiftcheck/llms.txt Use `ArrowOf` to generate arbitrary functions between two types. This allows testing higher-order functions and properties related to function behavior. ```swift import SwiftCheck // ArrowOf generates arbitrary functions! property("Map preserves structure") <- forAll { (xs: [Int], f: ArrowOf) in let fn = f.getArrow return xs.map(fn).count == xs.count } ``` -------------------------------- ### Negative Existential Test (Inverted Result) Source: https://context7.com/typelift/swiftcheck/llms.txt Tests that no integer equals its successor by inverting the result of an `exists` check. Requires SwiftCheck import. ```swift import SwiftCheck // Negative existential (there does not exist) property("No integer equals its successor") <- exists { (n: Int) in return n == n + 1 }.invert // Inverts the result ``` -------------------------------- ### Hide Test Output with Blind Source: https://context7.com/typelift/swiftcheck/llms.txt Use `Blind` to prevent generated values from being displayed in test output. This is useful for large data structures or sensitive information where verbose output is undesirable. ```swift import SwiftCheck // Blind hides values from test output (useful for large/sensitive data) property("Blind comparison") <- forAll { (x: Blind<[Int]>) in return x.getBlind == x.getBlind } // Output shows (*) instead of actual array values ``` -------------------------------- ### Generate Values from Full Range with Large Source: https://context7.com/typelift/swiftcheck/llms.txt Use `Large` to generate values across the entire possible range of the type, including minimum and maximum values. This ensures tests cover edge cases for integral types. ```swift import SwiftCheck // Large generates from the entire range of the type property("Large integers") <- forAll { (n: Large) in return n.getLarge >= Int64.min && n.getLarge <= Int64.max } ``` -------------------------------- ### SwiftCheck Disjunction Operator (^||^) Source: https://context7.com/typelift/swiftcheck/llms.txt Uses the disjunction operator to assert that at least one of the provided properties must hold true. Labels are used to identify which condition failed. ```swift import SwiftCheck // Disjunction (^||^) requires at least one property to hold property("Number is positive or negative or zero") <- forAll { (n: Int) in return (n > 0) "positive" ^||^ (n < 0) "negative" ^||^ (n == 0) "zero" } ``` -------------------------------- ### Prevent Shrinking with Static Source: https://context7.com/typelift/swiftcheck/llms.txt Use `Static` to disable the shrinking process for a generated value. This is helpful when shrinking might be complex, incorrect, or unnecessary for the property being tested. ```swift import SwiftCheck // Static prevents shrinking property("No shrinking") <- forAll { (x: Static) in return x.getStatic >= Int.min } ``` -------------------------------- ### Use explicit generators in properties Source: https://github.com/typelift/swiftcheck/blob/master/README.md Override implicit generator selection by passing a specific Gen instance to forAll. ```swift property("Gen.one(of:) multiple generators picks only given generators") <- forAll { (n1 : Int, n2 : Int) in let g1 = Gen.pure(n1) let g2 = Gen.pure(n2) // Here we give `forAll` an explicit generator. Before SwiftCheck was using // the types of variables involved in the property to create an implicit // Generator behind the scenes. return forAll(Gen.one(of: [g1, g2])) { $0 == n1 || $0 == n2 } } ``` -------------------------------- ### Generate Sorted Arrays with OrderedArrayOf Source: https://context7.com/typelift/swiftcheck/llms.txt Use `OrderedArrayOf` to generate arrays that are guaranteed to be sorted. This is ideal for testing algorithms that rely on or produce sorted data, such as binary search. ```swift import SwiftCheck // OrderedArrayOf generates pre-sorted arrays property("Binary search works on sorted arrays") <- forAll { (arr: OrderedArrayOf) in let sorted = arr.getOrderedArray return sorted == sorted.sorted() } ``` -------------------------------- ### Generate Non-Negative Values with NonNegative Source: https://context7.com/typelift/swiftcheck/llms.txt Use `NonNegative` to generate values greater than or equal to zero. This is suitable for scenarios like array indexing where negative indices are invalid. ```swift import SwiftCheck // NonNegative generates values >= 0 property("Array subscript is valid") <- forAll { (xs: [Int], idx: NonNegative) in return xs.isEmpty || idx.getNonNegative % xs.count >= 0 } ``` -------------------------------- ### SwiftCheck Verbose Equality Operator (====) Source: https://context7.com/typelift/swiftcheck/llms.txt Employs the verbose equality operator for checking equality, which prints the values of both sides upon failure, aiding in debugging. ```swift import SwiftCheck // Verbose equality operator (====) prints values on failure property("Sorting is idempotent") <- forAll { (xs: [Int]) in return xs.sorted().sorted() ==== xs.sorted() } ``` -------------------------------- ### SwiftCheck quickCheck Non-Asserting Variant Source: https://context7.com/typelift/swiftcheck/llms.txt Utilizes the non-asserting variant of the quickCheck function for reporting test results without causing failures, suitable for custom result handling. ```swift import SwiftCheck // Non-asserting variant for custom handling quickCheck(reporting: "Just report, don't fail") { forAll { (x: Int) in return x == x } } ``` -------------------------------- ### SwiftCheck once Modifier Source: https://context7.com/typelift/swiftcheck/llms.txt Applies the once modifier to run a property test only a single time, useful for quick checks or when the full test suite is not necessary. ```swift import SwiftCheck // once runs only a single test property("Singleton test") <- forAll { (x: Int) in return x == x }.once ``` -------------------------------- ### SwiftCheck Implication Operator (==>) Source: https://context7.com/typelift/swiftcheck/llms.txt Uses the implication operator to discard tests where the precondition fails, ensuring the property is only tested when the condition is met. ```swift import SwiftCheck // Implication operator (==>) discards tests where precondition fails property("Division is inverse of multiplication") <- forAll { (a: Int, b: Int) in return (b != 0) ==> { return (a * b) / b == a } } ``` -------------------------------- ### SwiftCheck verbose Modifier Source: https://context7.com/typelift/swiftcheck/llms.txt Enables verbose output for a property test using the verbose modifier, which prints every test case executed. This is helpful for detailed debugging. ```swift import SwiftCheck // verbose prints every test case property("Verbose output") <- forAll { (x: Int) in return x * 0 == 0 }.verbose ``` -------------------------------- ### SwiftCheck noShrinking Modifier Source: https://context7.com/typelift/swiftcheck/llms.txt Disables the shrinking process for a property using the noShrinking modifier. This can be useful when shrinking is not applicable or might obscure the root cause of a failure. ```swift import SwiftCheck // noShrinking disables shrinking on failure property("No shrink") <- forAll { (xs: [Int]) in return xs.count >= 0 }.noShrinking ``` -------------------------------- ### SwiftCheck expectFailure Modifier Source: https://context7.com/typelift/swiftcheck/llms.txt Uses the expectFailure modifier to indicate that a property is expected to fail. This is useful for testing invariants that should not hold under certain conditions. ```swift import SwiftCheck // expectFailure for properties that should fail property("Not all numbers are even") <- forAll { (n: Int) in return n % 2 == 0 }.expectFailure ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.