Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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: