Making four separate variables

2019-07-08 08:57发布

问题:

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))

回答1:

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


回答2:

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))
}


标签: ios swift xcode6