How to pick a random index from an array in Swift

2 Answers

0 votes
import Foundation

let arr = ["swift", "c", "c++", "python", "java", "rust"]

// Seeds the random number generator using the current time
srandom(UInt32(NSDate().timeIntervalSince1970))

// Picks a random index from the array and prints the selected item.
print(arr[random() % arr.count]);
 
 
 
/*
run:
 
java
 
*/

 



answered Aug 5, 2025 by avibootz
0 votes
import Foundation

let arr = ["swift", "c", "c++", "python", "java", "rust"]

// Seeds the random number generator using the current time
srandom(UInt32(NSDate().timeIntervalSince1970))

// Picks a random element and prints it
if let randomChoice = arr.randomElement() {
    print(randomChoice)
}
 
 
 
/*
run:
 
python
 
*/

 



answered Aug 5, 2025 by avibootz
...