Search code examples
iosswiftmodulooperationsarc4random

% operator giving strange result in swift ios


I am familiar with Mathematics and what the % operator (modulo) gives us for certain values. However, I am following along a Swift code lecture, and the instructor wants to return a value somewhere between 0 and half of the height of the view. He sets up the equation as:

var offSet = arc4random() % UInt32(self.frame.size.height / 2)

I must be missing something. Wouldn't arc give a number between 0 and 1, and then performing % on the height (roughly 700 pixels) would always give 0. Yet each time the code is run it offsets a random amount somewhere between 0 and half the height of the screen. If I change % to * the program crashes.

Ideas?


Solution

  • Read the arc4random() man page

    "arc4random() function returns pseudo-random numbers in the range of 0 to (2**32)-1"

    So your random number will be something potentially large, then the modulo will bring it into the range of 0 - (height/2 - 1)