Part of Swift with Copilot

Swift in VSCode: Create a list of 5 random numbers

Sandy LaneSandy Lane

Video: Swift in VSCode: Create a list of 5 random numbers by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

Swift with Copilot: Create a List of 5 Random Numbers

(1...5).map { _ in Int.random(in: 1...100) }. Range, map, and Int.random(in:) — three Swift idioms in one line. Copilot suggests this directly from the comment.

A 5-element random list is the simplest "build an array" exercise. Swift's range syntax and map make it a one-liner.

The Copilot prompt

// Create a list of 5 random numbers between 1 and 100

Copilot completes:

let randomNumbers = (1...5).map { _ in Int.random(in: 1...100) }
print(randomNumbers)

Output (different each run):

[42, 87, 13, 56, 91]

Walkthrough

(1...5).map { _ in Int.random(in: 1...100) }

Three pieces:

(1...5) — a closed range

a...b is the closed range [a, b] — both ends inclusive. Here it's 1, 2, 3, 4, 5.

a..<b is the half-open range [a, b)b excluded. So (0..<5) is 0, 1, 2, 3, 4.

For "5 elements," either works. The closed form is slightly more readable.

.map { ... } — transform each

map applies a closure to each element of a sequence, returning a new collection of the same length:

[1, 2, 3].map { $0 * 2 }
// [2, 4, 6]

$0 is the closure's first (and only) parameter. Since we don't use it, we can name it _:

(1...5).map { _ in 42 }
// [42, 42, 42, 42, 42]

Int.random(in: 1...100) — random integer

Int.random(in:) returns a uniformly random Int in the closed range:

Int.random(in: 1...100)    // 1 to 100 inclusive
Int.random(in: 0..<10)     // 0 to 9

Different types have their own:

Double.random(in: 0...1)
Bool.random()              // true or false

Combined: each map iteration produces a fresh random number.

Alternative: imperative

var numbers = [Int]()
for _ in 1...5 {
  numbers.append(Int.random(in: 1...100))
}
print(numbers)

Three lines instead of one. Both work; the map form is preferred — declarative, no mutable variable.

Reserve capacity for big arrays

var numbers = [Int]()
numbers.reserveCapacity(1000)
for _ in 0..<1000 {
  numbers.append(Int.random(in: 1...100))
}

For arrays you'll grow to a known size, reserveCapacity avoids repeated reallocations. Not needed for 5 elements.

Seeding

Swift's Int.random(in:) is uniformly distributed and uses the system random source. You can't seed it directly — each call is independent.

For reproducible randomness, use a custom generator:

import GameKit

let rng = GKMersenneTwisterRandomSource(seed: 42)
let numbers = (1...5).map { _ in rng.nextInt(upperBound: 100) + 1 }

GameKit ships with iOS/macOS. For server-side, third-party libraries like swift-random provide seedable generators.

Without duplicates

var seen = Set<Int>()
while seen.count < 5 {
  seen.insert(Int.random(in: 1...100))
}
let unique = Array(seen)
print(unique)

For 5 from 100, duplicates are rare but possible. Use a Set to deduplicate, then convert to Array. Order won't be guaranteed.

For "shuffle and take 5":

let unique = Array(1...100).shuffled().prefix(5)

shuffled() returns a randomly-ordered copy; prefix(5) takes the first 5.

More variations

// 5 random doubles
let floats = (0..<5).map { _ in Double.random(in: 0..<1) }

// 5 random booleans
let bools = (0..<5).map { _ in Bool.random() }

// 5 random elements from an array
let names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
let picked = (0..<3).map { _ in names.randomElement()! }

Array.randomElement() returns one random element (or nil if empty). The ! force-unwraps — safe here since names is non-empty.

For sampling without replacement, use shuffled().prefix(N).

Common stumbles

1..5 not valid. Swift uses ... (closed) or ..< (half-open). .. alone errors.

Int.random() no args. Needs (in: range). There's no zero-arg form.

map returns same-length collection. For different length, use compactMap (drop nils) or flatMap (flatten).

Integer division. 1 / 2 is 0 (Int). For 0.5, use Double.

Force-unwrap on empty. [].randomElement()! crashes. Use ?? for default: arr.randomElement() ?? 0.

What's next

Episode 3: Sort a list of numbers. sorted(), ascending/descending.

Recap

(1...5).map { _ in Int.random(in: 1...100) } — range + map + random. ... closed, ..< half-open. Int.random(in:), Double.random(in:), Bool.random(). For unique values, use Set or shuffled().prefix(N). For seeded randomness, use GameKit.GKMersenneTwisterRandomSource.

Next episode: sorting.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.