Swift
programming
error handling
modulo operator
truncatingRemainder

What does is unavailable Use truncatingRemainder instead mean?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Swift, the message telling you to use truncatingRemainder usually appears when % is used with floating-point values. The % operator is for integer modulo, while floating-point remainder uses a different API. Understanding this difference avoids type errors and subtle numeric bugs.

Why the Error Appears

Swift separates integer arithmetic from floating-point arithmetic intentionally. % is defined for integer types such as Int and UInt, but not for Double or Float.

Invalid example:

swift
let a: Double = 10.5
let b: Double = 3.0
// let r = a % b  // compile-time error

Correct floating-point version:

swift
1let a: Double = 10.5
2let b: Double = 3.0
3let r = a.truncatingRemainder(dividingBy: b)
4print(r)  // 1.5

Integer Modulo vs Floating Remainder

For integers, % works and is usually what you want.

swift
let x = 10
let y = 3
print(x % y)  // 1

For floating values, use truncatingRemainder(dividingBy:).

swift
let m = 10.5
let n = 3.0
print(m.truncatingRemainder(dividingBy: n))

This distinction keeps APIs explicit and prevents accidental coercions.

Negative Number Behavior

Remainder with negative inputs can surprise developers. Validate behavior in your domain.

swift
print((-10).quotientAndRemainder(dividingBy: 3).remainder) // -1
print((-10.5).truncatingRemainder(dividingBy: 3.0))       // -1.5

If your business rule needs always-positive modulo, normalize result manually.

swift
1func positiveModulo(_ a: Int, _ b: Int) -> Int {
2    let r = a % b
3    return r >= 0 ? r : r + b
4}

Choosing Numeric Types Deliberately

Many errors come from mixing Int and Double in the same calculation. Define numeric intent early.

  • Use integer math for counts, indices, and discrete cycles.
  • Use floating math for measurements and fractional values.

Converting between them should be explicit.

swift
1let count = 11
2let step = 4
3let wrap = count % step
4
5let distance: Double = 11.0
6let stride: Double = 4.5
7let phase = distance.truncatingRemainder(dividingBy: stride)

Helper Functions for Readability

Practical Use Cases

Remainder logic appears in progress indicators, animation phases, cyclic buffers, and periodic scheduling math. When values are fractional, using truncatingRemainder avoids unsafe integer coercion and keeps behavior aligned with floating-point domain expectations.

For user-facing calculations, round display values separately from internal remainder math so numeric precision and UI formatting concerns stay decoupled.

swift
let phase = 17.75.truncatingRemainder(dividingBy: 5.0)
let display = String(format: "%.2f", phase)
print(display)

This separation improves correctness and readability in production code.If remainder logic appears often, wrap it in clear helpers.

swift
1func fractionalPhase(_ value: Double, period: Double) -> Double {
2    precondition(period != 0)
3    return value.truncatingRemainder(dividingBy: period)
4}

This keeps call sites readable and centralizes edge-case handling.

Testing Numeric Edge Cases

Remainder operations should be tested with:

  • Zero divisors where invalid input should fail fast.
  • Negative operands.
  • Very small floating values.
  • Values near precision boundaries.

Floating-point tests should include tolerance checks rather than strict equality where appropriate.

Integer Conversion Caution

If you intentionally convert floating values to integers before using %, document rounding behavior clearly. Int conversion truncates toward zero, which can change expected remainder semantics in financial or scientific calculations.

swift
let value = 10.9
let integerRemainder = Int(value) % 3
print(integerRemainder)

Use this only when truncation is explicitly desired.## Common Pitfalls

  • Using % with Double or Float values.
  • Assuming integer and floating remainder semantics are identical.
  • Ignoring negative-result behavior in modulo logic.
  • Mixing numeric types without explicit conversions.
  • Skipping tests for divisor zero and boundary values.

Summary

  • '% in Swift is for integer modulo, not floating-point types.'
  • Use truncatingRemainder(dividingBy:) for Double and Float.
  • Validate remainder behavior for negative inputs.
  • Keep numeric type intent explicit in code design.
  • Add focused tests for edge cases and precision-sensitive values.

Course illustration
Course illustration

All Rights Reserved.