You can use arc4random_uniform
function to generate a random number and then convert it to boolean using a probability threshold. Here's an example code snippet that generates a random boolean with 50% probability of being true
:
main.swift115 chars5 lines
In the above code, arc4random_uniform(2)
generates a random integer between 0 and 1. If the integer is 1, the function returns true
, otherwise it returns false
. This results in a 50% probability of true
value. If you want to change the probability, you can modify the threshold accordingly. For example, to generate a random boolean with 80% probability of being true
, you can modify the code as follows:
main.swift165 chars6 lines
In the above code, arc4random_uniform(10)
generates a random integer between 0 and 9. If the integer is less than the threshold value of 8, the function returns true
, otherwise it returns false
. This results in a 80% probability of true
value.
gistlibby LogSnag