title: What is the best/shortest way to convert a UIColor to hex (web color) in Swift?
body: <p>I came up with the following solution, but would like to know if someone has a cleaner approach to it (tested it in Xcode-Playground):</p>
  
  <pre><code>let colors = CGColorGetComponents( UIColor.greenColor().CGColor )
  let hexCol:String = NSString(format: "#%02x%02x%02x", Int(colors[0] * 255.0), Int(colors[1] * 255.0), Int(colors[2] * 255.0))
  </code></pre>
  
  <p><code>resulting in #00ff00</code></p>
  
  <p>where UIColor.greenColor() is an example for any UIColor.</p>
  
  <p>edit:
  Taken from Leonardo's Answer, i felt like refactoring it a bit (all of his tests still apply).</p>
  
  <pre><code>extension UIColor {
      typealias RGBComponents = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
      typealias HSBComponents = (hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat)
  
      var rgbComponents:RGBComponents {
          var c:RGBComponents = (0,0,0,0)
  
          if getRed(&amp;c.red, green: &amp;c.green, blue: &amp;c.blue, alpha: &amp;c.alpha) {
              return c
          }
  
          return (0,0,0,0)
      }
  
      var cssRGBA:String {
          return String(format: "rgba(%d,%d,%d, %.02f)", Int(rgbComponents.red * 255), Int(rgbComponents.green * 255), Int(rgbComponents.blue * 255), Float(rgbComponents.alpha))
      }
      var hexRGB:String {
          return String(format: "#%02x%02x%02x", Int(rgbComponents.red * 255), Int(rgbComponents.green * 255), Int(rgbComponents.blue * 255))
      }
      var hexRGBA:String {
          return String(format: "#%02x%02x%02x%02x", Int(rgbComponents.red * 255), Int(rgbComponents.green * 255), Int(rgbComponents.blue * 255), Int(rgbComponents.alpha * 255) )
      }
  
      var hsbComponents:HSBComponents {
          var c:HSBComponents = (0,0,0,0)
  
          if getHue(&amp;c.hue, saturation: &amp;c.saturation, brightness: &amp;c.brightness, alpha: &amp;c.alpha) {
              return c
          }
  
          return (0,0,0,0)
      }
  }
  
  let v1 = UIColor.redColor().rgbComponents.red
  let v2 = UIColor.redColor().cssRGBA
  let v3 = UIColor.redColor().hexRGBA
  let v4test = UIColor.RGBComponents(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
  </code></pre>