Property-Based Testing Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Property-Based Testing runs in O(n) time and O(n) space, in Swift as in every other language.
- ✓Neither the standard library nor swift-testing / XCTest offers property testing. `SwiftCheck` (typelift/SwiftCheck, added via SwiftPM, `import SwiftCheck`) is the ecosystem answer: the `Arbitrary` protocol requires `static var arbitrary: Gen<Self>` and optionally `static func shrink(_:) -> [Self]`, `Gen<A>` composes with `.map`, `.flatMap`, `Gen.fromElements(of:)`, `Gen.frequency`, `.proliferate` and `.suchThat`, and properties read `property("name") <- forAll { (xs: [Int]) in ...
- ✓Reviewers want `Arbitrary` conformances declared in the test target only, so generator code never ships in the app binary, and they insist that a custom `Arbitrary` implement `shrink` -- the protocol's default returns an empty array, which silently disables shrinking for that type.
- ✓The Swift trap: Swift traps on integer overflow. `a + b` on generated `Int`s does not throw a catchable error and does not panic-with-unwind the way Rust does -- it calls `fatalError` and kills the process, so SwiftCheck never gets to report, let alone shrink, the counterexample.
- ✓`Gen<A>` is a struct wrapping a closure, so every `.map`/`.flatMap` in a generator chain allocates a boxed closure and pays ARC retain/release on each draw; a deep composition costs more per example than the property body.
What Property-Based Testing actually is
Property-Based Testing in Swift: what you actually reach for
Swift implementation
import SwiftCheck
struct Slug: Arbitrary, Equatable {
let raw: String
static var arbitrary: Gen<Slug> {
Gen<Character>
.fromElements(of: Array("abcdefghijklmnopqrstuvwxyz"))
.proliferate(withSize: 12)
.map { Slug(raw: String($0)) }
}
// Arbitrary's default shrink returns []; without this every
// counterexample stays 12 characters wide.
static func shrink(_ s: Slug) -> [Slug] {
String.shrink(s.raw).filter { !$0.isEmpty }.map { Slug(raw: $0) }
}
}
func runProperties() {
property("sorting is idempotent") <- forAll { (xs: [Int]) in
return xs.sorted().sorted() == xs.sorted()
}
// a + b would trap, killing the process before SwiftCheck can shrink.
property("addition never traps") <- forAll { (a: Int, b: Int) in
let (sum, overflowed) = a.addingReportingOverflow(b)
return overflowed ? sum == a &+ b : Int64(sum) == Int64(a) + Int64(b)
}
property("slugs stay lowercase") <- forAll { (s: Slug) in
return s.raw == s.raw.lowercased()
}
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Property-Based Testing?
Neither the standard library nor swift-testing / XCTest offers property testing. `SwiftCheck` (typelift/SwiftCheck, added via SwiftPM, `import SwiftCheck`) is the ecosystem answer: the `Arbitrary` protocol requires `static var arbitrary: Gen<Self>` and optionally `static func shrink(_:) -> [Self]`, `Gen<A>` composes with `.map`, `.flatMap`, `Gen.fromElements(of:)`, `Gen.frequency`, `.proliferate` and `.suchThat`, and properties read `property("name") <- forAll { (xs: [Int]) in ... }` where any `Bool` or `Testable` closes the law. For byte-level targets Swift also exposes libFuzzer directly via `swiftc -sanitize=fuzzer`.
What is the most common Swift mistake when implementing Property-Based Testing?
Swift traps on integer overflow. `a + b` on generated `Int`s does not throw a catchable error and does not panic-with-unwind the way Rust does -- it calls `fatalError` and kills the process, so SwiftCheck never gets to report, let alone shrink, the counterexample. You see a crash log, not a minimal failing input. Use `addingReportingOverflow`, `&+`, or bound the generator. The same trap fires on `Array` out-of-bounds and force-unwrapped `nil`, which generators find far faster than hand-written tests do -- so the first thing a new property usually buys you is a process abort with no diagnostic.
How does Property-Based Testing actually perform in Swift?
`Gen<A>` is a struct wrapping a closure, so every `.map`/`.flatMap` in a generator chain allocates a boxed closure and pays ARC retain/release on each draw; a deep composition costs more per example than the property body. Conformance to `Arbitrary` through an existential adds another box. Debug builds keep exclusivity checks and unspecialised generics live, so run the property suite with optimisation before drawing any conclusion about the code under test. SwiftCheck's default is 100 successful tests, tunable through `CheckerArguments`. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.