Legacy Random

ID

swift.legacy_random

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Swift

Tags

code-smell, modernization

Description

Reports calls to legacy C random APIs (arc4random, arc4random_uniform, rand, drand48, lrand48, mrand48, bare random). Swift’s standard library offers safer, range-based alternatives such as Int.random(in:) and Double.random(in:).

arc4random()                  // FLAW
arc4random_uniform(10)        // FLAW
rand()                        // FLAW
drand48()                     // FLAW

Int.random(in: 0..<10)        // OK
Double.random(in: 0..<1)      // OK

Rationale

The C random APIs predate Swift’s value types. They return platform fixed-width integers (UInt32, Int32) that callers must convert, they have modulo-bias gotchas (rand() % n), and they offer no ergonomic way to draw from a range that isn’t aligned to powers of two. Swift’s random(in:) family takes a Range / ClosedRange, returns the right type for the call site, and uses a better-quality PRNG by default (SystemRandomNumberGenerator).

Remediation

Replace the call with the matching random(in:):

let dice  = Int.random(in: 1...6)
let unit  = Double.random(in: 0..<1)
let bits  = UInt64.random(in: 0...UInt64.max)

For cryptographic-quality randomness, use SystemRandomNumberGenerator (default) or SecRandomCopyBytes directly.