在Swift中发生条件的机会:Xcode [英] Chance of a conditional occurring in Swift: Xcode

查看:58
本文介绍了在Swift中发生条件的机会:Xcode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Xcode还是很陌生,所以请迅速处理,如果这是一个不好的描述。有没有一种方法可以使您的条件发生,所以不是条件满足时100%的情况发生,而是条件满足时仅50%的情况发生?例如,

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,

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

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

非常感谢所有反馈!

推荐答案

您可以使用arc4random_uniform创建一个只读的计算属性以生成一个随机数并根据其结果返回一个布尔值。如果生成的数字等于1,则返回true;如果等于0,则返回false。结合if条件,仅当随机数等于1(true)时才可以在方括号内执行代码。

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
}

这篇关于在Swift中发生条件的机会:Xcode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆