Mick Mick - 4 years ago 98
iOS Question

How do i get data out of a while loop

The title pretty much says it all.

I have a function that generates random RGB values which are converted to a colour.

I only want colours within a specific Luminance range so im using a while loop to create the RGB values, then check the luminance with the idea being that i want it to keep looping until it generates a colour within the luminance range.

My problem is that i can not work out how to get data out of the while loop to use as part of the overall function

Edit:
the below isn't working, the while loop isn't returning a value for randomcolor, Xcode just gives an error stating it's being used before its initialized. even if I move the return statement up into the for loop I just get an error for the overall statement advising I haven't returned a UIcolor. What I'm trying to do is get the colour value out of the while loop so it can be used outside the while loop.

func randomColor() -> UIColor{
var randomRed:CGFloat
var randomGreen:CGFloat
var randomBlue: CGFloat
var randomcolor: UIColor
var lum: CGFloat = 0.0
while lum < 50.0 {
randomRed = CGFloat(arc4random_uniform(256))
randomGreen = CGFloat(arc4random_uniform(256))
randomBlue = CGFloat(arc4random_uniform(256))
lum = sqrt(randomRed * randomRed * 0.241 + randomGreen * randomGreen * 0.691 + randomBlue * randomBlue * 0.068)
if lum > 50.0{
let color = rC(randomRed: randomRed, randomBlue: randomBlue, randomGreen: randomGreen)
randomcolor = color

}
}
return randomcolor
}

Answer Source

Your problem is that you are declaring variables at the start of your function, but not initialising them. A value will be assigned to them inside the while loop, but the loop may execute zero times, resulting in randomcolor not being initialised before you attempt to reserve it.

Now, you and I can look at this code and see that lum is initialised with 0, so the while will execute at least once, but Swift doesn't work that way. It just sees that the only assignment is inside a conditional block, so it gets upset.

You can simplify your code a little to, by getting rid of the if statement:

func randomColor() -> UIColor {
    var randomRed:CGFloat = 0.0
    var randomGreen:CGFloat = 0.0
    var randomBlue:CGFloat = 0.0
    var lum: Float = 0.0

    while lum < 50.0 {
        randomRed = CGFloat(Float(arc4random_uniform(256)))
        randomGreen = CGFloat(arc4random_uniform(256))
        randomBlue = CGFloat(arc4random_uniform(256))
        lum = Float(sqrt(randomRed * randomRed * 0.241 + randomGreen * randomGreen * 0.691 + randomBlue * randomBlue * 0.068))
    }

    return rC(randomRed: randomRed, randomBlue: randomBlue, randomGreen: randomGreen)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download