Chance of a conditional occurring in Swift: Xcode

2019-09-21 16:12发布

问题:

I am quite new to Xcode and swift so sorry if this is a bad description. Is there a way that there is a chance of your conditional occurring so instead of it happening 100% of the time when the conditions are met, it only happens 50% of the time when the conditions are met? For example,

if (x = 10) { something will occur only 50% of the time or only has a chance of happening }

All feedback is greatly appreciated!

回答1:

You can use arc4random_uniform to create a read only computed property to generate a random number and return a boolean value based on its result. If the number generated it is equal to 1 it will return true, if it is equal to 0 it will return false. Combined with a if conditional you can execute the code inside the brackets only when the random number is equal to 1 (true).

let randomZeroOne = arc4random_uniform(2)

if randomZeroOne == 1 {
    print(randomZeroOne) // do this
} else {
    print(randomZeroOne) // do that
}

print(randomZeroOne == 1 ? "This" : "That")

Using this approach you can end up with something like this example bellow:

var trueFalse: Bool {
    return arc4random_uniform(2) == 1
}

print(trueFalse) // false
print(trueFalse) // true
print(trueFalse) // false


if trueFalse {
    // do that 50% odds
}


回答2:

The OP doesn't give much but @Leo got it right

if x == 10 {
    arc4random_uniform(2) == 0 ? dothis() : dothat()
}

Apple should rename that method and get rid of the pseudo one.