Random Numbers in Swift

swift random double
swift random number seed
unique random number generator swift
swift 5 random string
swift random() -> bool
swift random element from array
type 'int' has no member 'random'
swift secure random

I would like to create random numbers to be displayed in 5 UIImage boxes on the front of the app. However, I would like those numbers to not always be in the same range. For instance, my code below shows 0 ... 9 for randomPoolBallIndex3. But instead, I would like it to show any number from 0 ... 49 but not duplicate the same number on the other randomPoolBallIndex's. So every time the button is pressed it will not display, let's say 1, 1, 34, 35 and 50, but instead each number will be different.

Is there a way to pull this off?

I broke the array down from 0 ... 49 for each randomPoolBallIndex's but now they will only display what I have set the ranges for and I am not entirely happy, while it has resolved the duplication problem.

Code Below:

let ballArray = ["poolball1","poolball2","poolball3","poolball4","poolball5","poolball6","poolball7","poolball8","poolball9","poolball10","poolball11","poolball12","poolball13","poolball14","poolball15","poolball16","poolball17","poolball18","poolball19","poolball20","poolball21","poolball22","poolball23","poolball24","poolball25","poolball26","poolball27","poolball28","poolball29","poolball30","poolball31","poolball32","poolball33","poolball34","poolball35","poolball36","poolball37","poolball38","poolball39","poolball40","poolball41","poolball42","poolball43","poolball44","poolball45","poolball46","poolball47","poolball48","poolball49","poolball50"]

var randomPoolBallIndex: Int = 0
var randomPoolBallIndex1: Int = 0
var randomPoolBallIndex2: Int = 0
var randomPoolBallIndex3: Int = 0
var randomPoolBallIndex4: Int = 0
var randomPoolBallIndex5: Int = 0

@IBOutlet weak var poolBallView1: UIImageView!
@IBOutlet weak var poolBallView2: UIImageView!
@IBOutlet weak var poolBallView3: UIImageView!
@IBOutlet weak var poolBallView4: UIImageView!
@IBOutlet weak var poolBallView5: UIImageView!

@IBAction func buttonPressed(_ sender: UIButton) {
    randomPoolBallIndex1 = Int.random(in: 20 ... 29)
    randomPoolBallIndex2 = Int.random(in: 40 ... 49)
    randomPoolBallIndex3 = Int.random(in: 0 ... 9)
    randomPoolBallIndex4 = Int.random(in: 30 ... 39)
    randomPoolBallIndex5 = Int.random(in: 10 ... 19)

    poolBallView1.image = UIImage(named: ballArray[randomPoolBallIndex1])
    poolBallView2.image = UIImage(named: ballArray[randomPoolBallIndex2])
    poolBallView3.image = UIImage(named: ballArray[randomPoolBallIndex3])
    poolBallView4.image = UIImage(named: ballArray[randomPoolBallIndex4])
    poolBallView5.image = UIImage(named: ballArray[randomPoolBallIndex5])
Using Shuffled

I suppose you just need to get 5 different random pool ball names from your ballArray. So you don't need to generate any random numbers. Just in buttonPressed create a constant from shuffled ballArray

let shuffledBallArray = ballArray.shuffled()

now just set images like this:

poolBallView1.image = UIImage(named: shuffledBallArray[0])
poolBallView2.image = UIImage(named: shuffledBallArray[1])

So your buttonPressed action should look like this:

@IBAction func buttonPressed(_ sender: UIButton) {

    let shuffledBallArray = ballArray.shuffled()

    poolBallView1.image = UIImage(named: shuffledBallArray[0])
    poolBallView2.image = UIImage(named: shuffledBallArray[1])
    poolBallView3.image = UIImage(named: shuffledBallArray[2])
    poolBallView4.image = UIImage(named: shuffledBallArray[3])
    poolBallView5.image = UIImage(named: shuffledBallArray[4])
Creating Unique Random Numbers

Alternatively you can create function which gives you 5 unique random numbers

func generateNumbers(repetitions: Int, maxValue: Int) -> [Int] {

    var numbers = [Int]()

    for _ in 1...repetitions {
        var n: Int
        repeat {
            n = Int.random(in: 1...maxValue)
        } while numbers.contains(n)

    return numbers

and in buttonPressed just create constant for this array of random numbers and set images without saving any image names somewhere in ballArray with hardcoded 50 names

@IBAction func buttonPressed(_ sender: UIButton) {

    let randomNumbers = generateNumbers(repetitions: 5, maxValue: 50)

    poolBallView1.image = UIImage(named: "poolBall\(randomNumbers[0])")
    poolBallView2.image = UIImage(named: "poolBall\(randomNumbers[1])")
    poolBallView3.image = UIImage(named: "poolBall\(randomNumbers[2])")
    poolBallView4.image = UIImage(named: "poolBall\(randomNumbers[3])")
    poolBallView5.image = UIImage(named: "poolBall\(randomNumbers[4])")

How to generate random numbers in Swift – Hacking with Swift, How to generate random numbers in Swift. Smart, simple, and secure new ways to generate randomness. Paul Hudson March 29th 2019 @twostraws. Swift 4.2  For example, this generates a random number in the range 1 through 4, inclusive on both sides: let randomInt = Int.random(in: 1..<5) Similar methods exist for Float, Double, and CGFloat: let randomFloat = Float.random(in: 1..<10) let randomDouble = Double.random(in: 1100) let randomCGFloat = CGFloat.random(in: 11000) There’s even one for booleans, generating either true or false randomly: let randomBool = Bool.random()

Create an array. They allow for the storage of multitudes of data and you can reference all of them. Same for images

var randomPoolBallIndices:[Int]!
@IBOutlet weak var poolBallViews: [UIImageView]! //Look up how to make array from IBOutlets

override func viewDidLoad() {
    // Do any additional setup after loading the view, typically from a nib.
    randomPoolBallIndices = Array(repeating: 0, count: 5)

@IBAction func buttonPressed(_ sender: UIButton) {

    for index in randomPoolBallIndices.indices {
        let number = Int.random(in: 0 ... 49)
        while (randomPoolBallIndices.contains(number)) {
            number = Int.random(in: 0 ... 49)
        randomPoolBallIndices[index] = number
        poolBallViews[index] = randomPoolBallIndices[index]

random(in:), Returns a random value within the specified range. SDK. Xcode 10.0+. Framework. Swift Standard Library. The generation of random numbers in Swift begins with RandomNumberGenerator — a protocol that does nothing but generate random UInt64 values: public protocol RandomNumberGenerator { mutating

Generate random number and insert it in Set. When Set count reaches 5, break the loop. That way you can avoid duplication. Then create array of random numbers from set.

How does one generate a random number in Apple's Swift language , Swift 4.2+. Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types. You can call the random() method on numeric  Dealing with randomness regardless of Swift version arc4random (). Where a particular set of numbers often appear more than others. Thus, it undermines the “randomness” of arc4random_uniform (n). It returns a random number between 0 and upper_bound minus 1. drand48 (). Working with random

Swift Random Numbers, Randomness or a random number has many uses, this includes: picking a lottery winner from a list; generating a unique id/session for a user; adding an element  The default random number generator has been renamed from Random.default to SystemRandomNumberGenerator() during the Swift 4.2 beta phase. Working with random numbers in Swift used to be a bit of pain because there was no native random number API.

Generating random numbers in Swift, You can simply generate a random number from int min to int max by using the nextInt() method on any of the sources mentioned above or from 0  This seems to be the way in Swift to generate a random number, based on the book released from Apple. protocol RandomNumberGenerator { func random() -> Double } class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ( (lastRandom * a + c) % m) return lastRandom / m } } let generator = LinearCongruentialGenerator() for _ in 1..10 { // Generate "random" number from 1-10

Random numbers in Swift – Ole Begemann, Swift 4.2 makes this much easier by including a native and fairly full-featured random number API in the standard library. You can read about the  A custom Random Number Generator type can have different characteristics than the default System Random Number Generator type. For example, a seedable generator can be used to generate a repeatable sequence of random values for testing purposes. To make a custom type conform to the Random Number Generator protocol, implement the required next

  • Have a look here
  • var ballArray2 = ballArray; random1 = Int.random(in 0 ... ballArray2.count), view1 = UIImage(named: ballArray2[random1]); ballArray.remove(at: random1), random2 = Int.random(in: 0 ... ballArray2.count); etc.? Not sure of the limit, might be ballArray2.count-1
  • I like this solution, another option is to have array property with last selcted values and one function wich can check if the number is already selected to get another one.
  • shuffle() shuffles the collection in place. Use shuffled() instead.
  • Hi Robert, The First answer you gave me so far seems to work pretty well, am i right in assuming, I will not get duplicate numbers like two 1's or two 49's or anything else being displayed?
  • Well You have earned yourself a Tick sir, and Thank you very much for your assistant. It goes towards my learning experience of Swift and programming in general. Thanks again