Can I set a range of numbers when using arc4random()? For example 50-100 only.
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- Swift - hide pickerView after value selected
- How can I add media attachments to my push notific
Will generate
randon number
between10
and30
, i.e.11,12,13,14......29
In many situations 10 thru 30 would mean inclusive, (includes 10 and 30) ...
Notice the difference toNumber - fromNumber is now 21 ... (20+1) which yields the possible results of 0 thru 20 (inclusive) which when added to fromNumber (10) results in 10 thru 30 (inclusive).
To expand upon JohnK comment.
It is suggested that you use the following function to return a ranged random number:
which will return a random number in the range
0
to50
.Then you can add your lower bounds to this like:
which will return a random number in the range
50
to100
.The reason we use
arc4random_uniform(51)
overarc4random() % 51
is to avoid the modulo bias. This is highlighted in the man page as follows:In short you get a more evenly distributed random number generated.
As pointed out in other posts below, it is better to use
arc4random_uniform
. (When this answer was originally written,arc4random_uniform
was not available). Besides avoiding the modulo bias ofarc4random() % x
, it also avoids a seeding problem witharc4random
when used recursively in short timeframes.will generate 0, 1, 2 or 3. Thus you could use:
and merely add 50 to the result to get a range between 50 & 100 (inclusive).
In Swift you can use this (inspired by answer of @Justyn)
Will always give you a random range Integer.
You can use this code for generating random values with range: