Search code examples
swiftrandomconstantsarc4random

Why arc4random_uniform can be set as a constant?


Why arc4random_uniform can be set as a constant? I noticed that in multiple examples. arc4random_uniform generates a new value every time it is called and I thought value of a constant should never change? It looks much more like a variable.


Solution

  • This is confusing.

    You can make a thing a constant. In this case, the thing is a function. You're setting up a constant reference to a function. Think of arc4random_uniform() as a random number factory. It is constant. It sits there, waiting to create random numbers, just like a car factory, sits their waiting to create cars.

    When you call the random number factory, it gives you a new random number, but the thing itself, the random number factory, remains constant.

    Edit:

    If you had a variable reference to a function instead, then you could store different random number factories in that variable. Each one might have different performance characteristics (speed, true randomness of the results, range of results, etc.)