Swift 中条件发生的几率:Xcode

Chance of a conditional occurring in Swift: Xcode

我对 Xcode 和 swift 很陌生,如果描述有误,我深表歉意。有没有一种方法可以让您的条件发生,而不是在满足条件时 100% 的时间发生,而只有 50% 的时间在满足条件时发生?例如,

如果(x = 10){ 某事只会在 50% 的时间内发生或只有机会发生 }

非常感谢所有反馈!

您可以使用 arc4random_uniform 创建一个只读计算 属性 来生成一个随机数,并 return 根据其结果生成一个布尔值。如果生成的数字等于 1,则 return 为真,如果等于 0,则为 return 假。结合 if 条件,只有当随机数等于 1(真)时,您才能执行括号内的代码。

let randomZeroOne = arc4random_uniform(2)

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

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

使用这种方法,您可以得到如下示例所示的结果:

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

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


if trueFalse {
    // do that 50% odds
}

OP 提供的不多,但@Leo 做对了

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

Apple 应该重命名该方法并删除伪方法。