[swift-evolution] 'Random' Improvements

Pedro Ferreira plferreira4 at gmail.com
Sun Apr 2 11:41:09 CDT 2017

Hello, not sure if this has been discussed before, but I would like to say
a suggestion of something that could be added to swift's standard library.

Right now if you want to get a random number, you need to do it differently
depending on whether you're on macOS or linux (or do both). In linux you
would use the 'random()' function from 'Glibc', and in macOS you would use
the 'arc4random_uniform()' from 'Darwin'.

Given how common it is to want to get a random number, I feel like it would
be worthwhile to have a function in the standard library that deals with
these differences, so that you can just get a random number and not have to
worry about the different OS.
So basically, you would simply import 'Foundation', and then use a standard
'random()' function.

Even better if you also add some helper functions, like a get random
int/float with range parameters.

For example, a possible implementation could be:

import Foundation

    // so we get different numbers every run

func getRandom(_ min: Int, _ max: Int) -> Int {
    let diff = max - min + 1

    #if os(Linux)
        return min + Int(random() % diff)
        return min + Int(arc4random_uniform(UInt32(diff)))

print(getRandom(50, 100))

Just an idea, thanks for reading, cheers.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170402/b295b03b/attachment.html>

More information about the swift-evolution mailing list