Making four separate variables

2019-07-08 08:49发布

I am trying to make four separate variables that are all different so that a and b are different, a and c are different, b and c are different and so on so forth. Here are the four variables.

var a = Int(arc4random_uniform(5))
var b = Int(arc4random_uniform(5))
var c = Int(arc4random_uniform(5))
var d = Int(arc4random_uniform(5))

标签: ios swift xcode6
2条回答
叛逆
2楼-- · 2019-07-08 09:03
let a = Int(arc4random_uniform(5))
var b = Int(arc4random_uniform(5))
while b == a {
    b = Int(arc4random_uniform(5))
}
var c = Int(arc4random_uniform(5))
while c == a || c == b {
    c = Int(arc4random_uniform(5))
}
var d = Int(arc4random_uniform(5))
while d == c || d == b || d == a {
    d = Int(arc4random_uniform(5))
}
println(a)  // 2
println(b)  // 0
println(c)  // 4
println(d)  // 3
查看更多
Emotional °昔
3楼-- · 2019-07-08 09:25

Even though the question has been already answered, here is an alternative solution:

var set = Set<UInt32>()

while set.count < 4 {
    set.insert(arc4random_uniform(5))
}
查看更多
登录 后发表回答