Get Random Value In Swift

Creating random value is useful when you need the order of doing something that isn’t important, for example, the next song in the music player when shuffle mode is on or tips about your app.

We call it random, but in computer science, most cases talk about pseudo-random – Wikipedia.

In new Swift version, we have built it .random(in:) and .randomElement() functions.

Bool

let randomBool = Bool.random()

As it’s easy to guess randomBool has true or false, there can’t be any other value.

Int, Float, Double, UInt8, CGFloat…

The numeric variables have random(in:) which get one value from the range which you pass.

It can be opened and closed range.

Float.random(in: 1…10)

The result can be 1.0, 2.0, 3.4, 4.523, 7.777, …, or 10.0
Min value is 1.0 and the max is 10.0 because it’s closed ranged.

Int.random(in: 3..<5)

The result can be only 3 and 4 because there can be an only integer number and it’s opened the range and upper bound is less than 5.

Character and String

String doesn’t have .random(in:) but it had .randomElement() which returns one Character from current string.

let someText = “SmashSwift”
someText.
randomElement()

The result will be any Character which is in SmashSwift.

Character doesn’t have neither .random(in:) nor .randomElement(). To get random Character from English alphabet you need to create String with all letters and then use .randomElement().

let randomCharacter = “abcdefghijklmnopqrstuvwxyz”.randomElement()

Collections

It works in the same way as in String, arrays and dictionaries have .randomElement() which returns one element form collection.

let array = [“This”,“is”,“a”,“test”,“array”]
array.
randomElement()

let dictnionary: [String : Any] = [“Smash”: “Swift”, “error”: 404]
dictnionary.
randomElement()

Dictionary’s .randomElement() returns key-value tuple.