1
func randomCGFloat() -> CGFloat {
    return CGFloat(arc4random()) / CGFloat(UInt32.max)
}

extension UIColor
{
    static func randomColor() -> UIColor {
        let r = randomCGFloat()
        let g = randomCGFloat()
        let b = randomCGFloat()
        return UIColor(red: r, green: g, blue: b, alpha: 1.0)
    }

This is the code i am using in order to produce a random color. My question is the following. Can i get the r,g,b parameters once i call the randomColor() function twice? for example

`randomColor()` ->>> call
print the r,g,b
`randomColor()` ->>> call
print the r,g,b

Since it's a random number generator in order to produce a random color, i am afraid that every time i will try to access one of those variables inside the function i will get different results, since once it will be recalled(?). Help would be appreciated.If there is a different approach feel free to use it.

Korpel
  • 2,432
  • 20
  • 30

2 Answers2

1

It won't be recalled. Once you assign a variable as your randomCGFloat it gets locked in. Reading the value won't randomize it again. The only thing that will randomize it again is calling is saying r = randomCGFloat() again.

To print, just print as you normally would. Maybe println(NSString("RGB: %.2f %.2f %.2f", r, g, b)) right before your return UIColor line of code.


func randomCGFloat() -> CGFloat {
    return CGFloat(arc4random()) / CGFloat(UInt32.max)
}

extension UIColor
{
    static func randomColor() -> UIColor {
        let r = randomCGFloat()
        let g = randomCGFloat()
        let b = randomCGFloat()
        println(NSString("RGB: %.2f %.2f %.2f", r, g, b))
        return UIColor(red: r, green: g, blue: b, alpha: 1.0)
    }
Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
  • Hm that's an approach i didn't think about it. You are actually implementing the `print` inside of the function. – Korpel Feb 03 '16 at 10:06
1

You can use standard UIColor method getRed(_, green:, blue:, alpha:):

    var r: CGFloat = 0
    var g: CGFloat = 0
    var b: CGFloat = 0
    var a: CGFloat = 0
    UIColor.randomColor().getRed(&r, green: &g, blue: &b, alpha: &a)

    print("R: \(r), G: \(g), B: \(g), A: \(g)")
Greg
  • 25,317
  • 6
  • 53
  • 62
  • i am a newbie to swift. Are those `&r` considered a pointer? or you just define that you are assigning the Red value to the variable `r`? – Korpel Feb 03 '16 at 10:04
  • @Korpel Thats from Swift documentation: You place an ampersand (&) directly before a variable’s name when you pass it as an argument to an in-out parameter, to indicate that it can be modified by the function. – Greg Feb 03 '16 at 16:58
  • really thanks for your help. Really appreciate! – Korpel Feb 03 '16 at 17:28