Call Int.random(in:) with a range: Int.random(in: 1...6) gives 1 to 6, both ends included, and Int.random(in: 1..<7) gives the same numbers. Double.random(in: 0..<1) and Bool.random() work the same way. For arrays, array.randomElement() picks one item (it returns an optional) and array.shuffled() returns the items in random order. No import is needed.
Since Swift 4.2 the standard library has its own random API: every integer and floating-point type has a random(in:) method, collections have randomElement(), shuffled() and shuffle(), and all of them draw from the system generator unless you pass your own. That replaced the older arc4random_uniform answers you still find on Stack Overflow. The sections below cover numbers in a range, random elements and shuffling, a seeded generator for repeatable tests, picks without repeats and weighted picks, and what happens to arc4random_uniform on Linux, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1Int.random(in:) and friendsRecommended
Int.random(in:) takes either a closed range, 1...6, which includes the upper bound, or a half-open range, 1..<7, which stops just before it. Every value in the range is equally likely. Double, Float and every integer type such as Int8 or UInt64 have the same method, and Bool.random() takes no range at all. Because the output changes on every run, the program below prints facts about the numbers rather than the numbers themselves.
// A die roll: 1...6 is a closed range, both ends included let roll = Int.random(in: 1...6) print("roll is in 1...6:", (1...6).contains(roll)) // Draw 1,000 times and collect the distinct values let closed = (1...1_000).map { _ in Int.random(in: 1...6) } let halfOpen = (1...1_000).map { _ in Int.random(in: 1..<6) } print("1...6 gave", Set(closed).sorted()) print("1..<6 gave", Set(halfOpen).sorted()) // Double and Float take a range too; Bool.random() is a coin flip let price = Double.random(in: 10.0..<20.0) print("price in 10..<20:", price >= 10 && price < 20) let angle = Float.random(in: 0...360) print("angle in 0...360:", angle >= 0 && angle <= 360) let heads = (1...1_000).filter { _ in Bool.random() }.count print("heads in 400...600:", (400...600).contains(heads)) // Any integer type works, including negative ranges let offset = Int8.random(in: -5...5) print(type(of: offset), (-5...5).contains(offset))
Output
A thousand draws from 1...6 produce every value from 1 to 6, while 1..<6 never produces 6: [1, 2, 3, 4, 5]. That is the off-by-one to watch when you port code from languages whose random functions exclude the top. The Double and Float draws land inside their ranges, about half of the coin flips come up true, and Int8.random(in: -5...5) returns an Int8. The range must not be empty or backwards: Int.random(in: 5...1) compiles but crashes with Fatal error: Range requires lowerBound <= upperBound.
2Pick a random element, shuffle an array
randomElement() picks one item from any collection: an array, a range, a string or a dictionary. It returns an optional because an empty collection has nothing to pick, so unwrap it with if let or ??. When you need the position as well, Int.random(in: array.indices) gives a valid index. To put a whole array in random order, shuffled() returns a new array and shuffle() reorders a var in place.
let colors = ["red", "green", "blue", "yellow"] // randomElement() returns an optional: the array could be empty if let pick = colors.randomElement() { print("picked one of the colors:", colors.contains(pick)) } let none: [String] = [] print("from an empty array:", String(describing: none.randomElement())) // It works on any collection: ranges, strings, dictionaries if let n = (1...100).randomElement(), let c = "SWIFT".randomElement() { print("n in 1...100:", (1...100).contains(n), "letter:", "SWIFT".contains(c)) } // A random index, when you need the position too let i = Int.random(in: colors.indices) print("random index is valid:", colors.indices.contains(i)) // shuffled() returns a new array and leaves the original alone let mixed = colors.shuffled() print("same colors:", mixed.sorted() == colors.sorted(), "original:", colors) // shuffle() mixes a var in place var deck = Array(1...52) deck.shuffle() print("52 different cards:", Set(deck).count == 52) print("moved from 1...52 order:", deck != Array(1...52))
Output
The pick is always one of the colors, and the empty array gives nil instead of crashing. shuffled() holds the same four colors in a new order while the original still prints as ["red", "green", "blue", "yellow"], and after shuffle() the deck still holds 52 different cards, no longer in order. Both use the Fisher-Yates algorithm, so every order is equally likely. A plain let array can't call shuffle(); use shuffled() or declare it with var.
3Repeatable random numbers with a seeded generator
The default generator, SystemRandomNumberGenerator, seeds itself and can't be seeded by you, so there is no srand(42) for Int.random. For tests, simulations and games that need the same sequence every time, write a type that conforms to RandomNumberGenerator: it only needs a mutating func next() -> UInt64. Then pass it with using: &rng, which every random API accepts: Int.random(in:using:), shuffled(using:), randomElement(using:), Bool.random(using:). The one below is SplitMix64, a well-known 64-bit generator that fits in ten lines. It is fine for tests and games, not for passwords or keys.
// SplitMix64: a small, fast generator you can seed struct SplitMix64: RandomNumberGenerator { private var state: UInt64 init(seed: UInt64) { state = seed } mutating func next() -> UInt64 { state &+= 0x9E37_79B9_7F4A_7C15 var z = state z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB return z ^ (z >> 31) } } // Pass the generator with using: &rng to any random API var rng = SplitMix64(seed: 42) let rolls = (1...10).map { _ in Int.random(in: 1...6, using: &rng) } print("rolls:", rolls) print("shuffled:", ["a", "b", "c", "d", "e"].shuffled(using: &rng)) let pick = ["red", "green", "blue"].randomElement(using: &rng) print("pick:", pick ?? "none") print("coin:", Bool.random(using: &rng)) // The same seed gives the same sequence, every run var first = SplitMix64(seed: 7) var second = SplitMix64(seed: 7) let a = (1...5).map { _ in Int.random(in: 1...100, using: &first) } let b = (1...5).map { _ in Int.random(in: 1...100, using: &second) } print(a, a == b) // Code under test takes any generator; the app passes the system one func rollDice<G: RandomNumberGenerator>( _ count: Int, using rng: inout G ) -> [Int] { (0..<count).map { _ in Int.random(in: 1...6, using: &rng) } } var testRng = SplitMix64(seed: 1) print("test:", rollDice(3, using: &testRng)) var system = SystemRandomNumberGenerator() print("real:", rollDice(3, using: &system).count, "dice")
Output
Run it twice and every line comes out the same: seed 42 always rolls [5, 1, 2, 3, 1, 6, 2, 5, 3, 4] and shuffles the letters to ["b", "c", "d", "e", "a"], and two generators with seed 7 agree ([39, 2, 91, 59, 46] true). The generator is passed inout, hence the & and the var: each call moves its state forward. rollDice shows the usual way to make random code testable: take any generator as a parameter, pass a seeded one in tests and SystemRandomNumberGenerator() in the app. One caution: the standard library documents that the way it turns generator output into a range may change in a future Swift version, so don't store these exact values as long-lived test fixtures across compiler upgrades.
4Random picks without repeats, and weighted picks
Calling Int.random several times can return the same number twice. To draw distinct values, shuffle the candidates and take a prefix: (1...49).shuffled().prefix(6) is a lottery draw. When the range is huge and you need only a few values, shuffling millions of numbers is wasteful; insert into a Set until it holds enough. For a weighted choice, roll a number below the total weight and walk the list, subtracting each weight until the roll falls inside one.
// Six different numbers from 1 to 49: shuffle, then take a prefix let draw = (1...49).shuffled().prefix(6).sorted() print("count:", draw.count, "all different:", Set(draw).count == 6) print("all in 1...49:", draw.allSatisfy { (1...49).contains($0) }) // For a few picks from a huge range, fill a Set instead var ids = Set<Int>() while ids.count < 5 { ids.insert(Int.random(in: 1...1_000_000)) } print("unique ids:", ids.count) // Weighted choice: roll below the total weight, then walk the list let loot = [("common", 70), ("rare", 25), ("legendary", 5)] let totalWeight = loot.reduce(0) { $0 + $1.1 } func pickLoot() -> String { var roll = Int.random(in: 0..<totalWeight) for (name, weight) in loot { if roll < weight { return name } roll -= weight } return loot[0].0 // not reached while the weights add up } var counts = ["common": 0, "rare": 0, "legendary": 0] for _ in 1...10_000 { counts[pickLoot(), default: 0] += 1 } print("common near 7,000:", (6_500...7_500).contains(counts["common"] ?? 0)) print("rare near 2,500:", (2_000...3_000).contains(counts["rare"] ?? 0)) print("legendary near 500:", (350...650).contains(counts["legendary"] ?? 0))
Output
The lottery draw always holds six different numbers in range, and the Set ends with five unique ids because inserting a repeat does nothing. Over 10,000 weighted picks, each loot type lands near its share of the total weight of 100: about 7,000 common, 2,500 rare and 500 legendary. The checks allow a margin because the exact counts change on every run. prefix(6) returns an ArraySlice; sorted() turns it back into an array, or wrap it in Array(…) if you want to keep the shuffled order.
5arc4random_uniform: the old answer
Before Swift 4.2, the usual answer was Int(arc4random_uniform(6)) + 1: a C function from Apple's Darwin library that returns a UInt32 from 0 up to, but not including, its argument. It still works in apps on Apple platforms, but it isn't part of Swift: on Linux it comes from the C library only in glibc 2.36 and later, and this page runs on Ubuntu 22.04 (glibc 2.35), so the program below does not compile, even with import Foundation.
import Foundation // The pre-Swift 4.2 answer: works on Apple platforms only let roll = Int(arc4random_uniform(6)) + 1 print(roll)
Output
The compiler stops with error: cannot find 'arc4random_uniform' in scope. Replace line 4 with let roll = Int.random(in: 1...6) and run it again: the result is the same range, already an Int, and the code compiles on every platform Swift supports. The same goes for arc4random() and drand48() in old answers: use UInt32.random(in:) and Double.random(in: 0..<1) instead.
6Which should you use?
| Method | Returns | Seedable | Best for |
|---|---|---|---|
| Int.random(in: a...b) | A number in the range | With using: | Almost everything: dice, ids, delays |
| Double.random(in:), Bool.random() | A Double or Bool | With using: | Fractions, probabilities, coin flips |
| array.randomElement() | Optional item | With using: | Picking one item |
| shuffled() / shuffle() | New array / in place | With using: | Random order, picks without repeats |
| Custom RandomNumberGenerator | Same sequence per seed | Yes | Tests, replays, procedural content |
| arc4random_uniform(n) | UInt32, not portable | No | Old code; replace it |
Frequently asked questions
How do I generate a random number between two numbers in Swift?
Use Int.random(in: low...high), which includes both ends, or Int.random(in: low..<high), which leaves out high. For decimals use Double.random(in: low..<high). The bounds can be variables, so Int.random(in: min...max) works as long as min <= max.
Why does Int.random(in: 5...1) crash?
Because 5...1 is not a valid range: the lower bound must not be greater than the upper one. The program stops with Fatal error: Range requires lowerBound <= upperBound. An empty half-open range such as 3..<3 fails inside random instead, with Fatal error: Can't get random value with an empty range. When the bounds come from input, check them first, or order them with Int.random(in: min(a, b)...max(a, b)).
Can I seed the random number generator in Swift?
Not the default one: SystemRandomNumberGenerator seeds itself and has no seed parameter. Write your own type that conforms to RandomNumberGenerator (it needs only mutating func next() -> UInt64), create it with a seed, and pass it with using: &rng to Int.random(in:using:), shuffled(using:) or randomElement(using:). SplitMix64 in section 3 is a common choice.
How do I pick a random element from an array?
Call array.randomElement(). It returns an optional, nil for an empty array, so write if let item = array.randomElement() { … } or array.randomElement() ?? fallback. If you also need the index, use Int.random(in: array.indices) and read array[index].
How do I shuffle an array in Swift?
Call shuffled() to get a new array in random order, or shuffle() to reorder a var array in place. Both use the Fisher-Yates algorithm. To draw n distinct items, shuffle and take a prefix: Array(items.shuffled().prefix(n)).
Is Int.random secure enough for passwords and tokens?
The default SystemRandomNumberGenerator is documented as using a cryptographically secure algorithm whenever possible, with the operating system as its source. A seeded generator you write, like SplitMix64, is not: anyone who knows the seed can repeat the sequence. Use it for tests and games only.
Does C's random() work instead?
On Linux it compiles with import Foundation, but without a call to srandom it starts from the same seed every time: here, print(random(), random()) printed 1804289383 846930886 on every run. Use Int.random(in:) instead: it needs no import and no seeding.