Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build a Playlist Browser with Swift Building the Music Library and Playlist Models Using a Playlist Instance

Sahit penmatcha
Sahit penmatcha
4,555 Points

Why do you have to make it take in a CGFloat? What is that?

why do you have to make it take in a CGFloat? What is that?

func rgbColorFromDictionary(colorDictionary :[String: CGFloat]) -> UIColor{

    let red = colorDictionary["red"]!
    let green = colorDictionary["green"]!
    let blue = colorDictionary["blue"]
    let alpha = colorDictionary["alpha"]

    return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha)

}

2 Answers

A CGFloat is basically a typdef for a float. A float is a number with decimals to ^7 (I dont know if CGFloat spec differs).

Take this for example;

  • 1685.3829268 = Float

If you declared that as a Float or CGFloat then it would be stored in memory as that. If you stored it as an int It would be stored as 1685 only.

Its interesting to note that a Double is 2x as more accurate (if you were ever going for accuracy) - a double can store 15-16 decimal digits precisely whereas a float will only do 7.

Hope this helps.

Regina Soifer
Regina Soifer
7,386 Points

CGFloat is just a type definition for either float or double. You can see for yourself by Command-double-clicking on "CGFloat" in Xcode

These types were introduced to make it easier to write code that works on both 32-bit and 64-bit without modification. However, if all you need is float precision within your own code, you can still use float if you like — it will reduce your memory footprint somewhat.

This answer came from StackOverflow:

http://stackoverflow.com/questions/1264924/whats-the-difference-between-using-cgfloat-and-float