在 Swift 中,我使用arc4random生成0到568之间的数字。
我需要它对此施加限制。例如,数字不能介于10到40之间。这些限制如何"加入?
答案 0 :(得分:4)
继续尝试直到满足条件:
func funnyRandom() -> UInt32 {
var ran: UInt32 = 0
do {
ran = arc4random_uniform(568)
} while (ran > 10 && ran < 40)
return ran;
}
在Objective-C中,它与Swift中的方法相同:
- (int)funnyRandom {
int ran;
do {
ran = arc4random_uniform(568);
} while (ran > 10 && ran < 40);
return ran;
}
答案 1 :(得分:3)
多次调用arc4random_uniform
func funnyRandom() -> UInt32 {
var ran: UInt32 = 0
//we have less values
ran = arc4random_uniform(568 - 40 + 10)
//skip the excluded range
if (ran > 10) {
ran += 40 - 10
}
}
更一般地说:
func funnyRandom(max: UInt32, excludeRange: Range<UInt32>) -> UInt32 {
var excludeRangeLength = excludeRange.endIndex - excludeRange.startIndex + 1
var random: UInt32 = arc4random_uniform(max - excludeRangeLength)
if (random >= excludeRange.startIndex) {
random += excludeRangeLength
}
return random
}
funnyRandom(568, excludeRange: 10...40)