Back to Blog

Swift: Create a random list of 5 numbers between 1 to 100

Sandy LaneSandy Lane

Video: Swift: Create a random list of 5 numbers between 1 to 100 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift: Create a Random List of 5 Numbers Between 1 to 100

Generating random numbers in Swift is straightforward using the built-in random API. This example demonstrates how to create a list of 5 random integers, each ranging from 1 to 100, using a simple loop and Swift's random number generation methods.

Code

import Foundation

// Create an empty array to hold the random numbers
var randomNumbers: [Int] = []

// Generate 5 random numbers between 1 and 100
for _ in 1...5 {
  let number = Int.random(in: 1...100)  // Generate a random Int from 1 to 100
  randomNumbers.append(number)           // Add the number to the array
}

print(randomNumbers)  // Output the list of random numbers

Key Points

  • Use Int.random(in:) to generate a random integer within a specified range.
  • A for-loop can be used to repeat the random number generation multiple times.
  • Appending each generated number to an array collects the results for later use.
  • The range 1...100 includes both 1 and 100 as possible values.
  • This approach can be easily adapted for different ranges or list sizes.