generate random boolean in swift

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.swift
func generateRandomBoolean() -> Bool {
    let randomNumber = arc4random_uniform(2)
    return randomNumber == 1
}
115 chars
5 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.swift
func generateRandomBoolean() -> Bool {
    let threshold = 8  // 80% probability
    let randomNumber = arc4random_uniform(10)
    return randomNumber < threshold
}
165 chars
6 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