Doug Smith
Doug Smith

Reputation: 29326

Should we be using CGFloat for all floating point numbers in Swift?

After watching a lot of the WWDC videos and reading through the Swift iBook, I came away with the impression that CGFloat was somewhat... legacy, due to the emphasis on Int and Double/Float. Perhaps somewhat comparable to NSString vs String.

I wrote a bit of code with the latter, and Double won't compile on non-64 bit devices. Int seems fine, though.

Should we still be using CGFloat for all math? Has anyone found anything that would indicate we'd be able to use the native Swift numerics? Because right now they're essentially unusable outside of scripts.

Upvotes: 4

Views: 1115

Answers (2)

Daveloper
Daveloper

Reputation: 656

I faced the problem when I was "fetching" from UserDefaults.

I saved float data like:

let floatValue: CGFloat = 1.3
UserDefaults.standard.set(floatValue, forKey: "Key")

Then I wanted to fetch it and parse it as a CGFloat

let floatValue = CGFloat(UserDefaults.standard.float(forKey: "Key"))

It made from 1.3 value - 1.29999...

So when you save/load to/from UserDefaults you should use Float. Otherwise, I use CGFloat and there is no problem with it.

Upvotes: 0

Connor
Connor

Reputation: 64684

According to Chris Lattner, they recognize this problem and will have an official solution soon. I'd wait until this solution is fixed before deciding whether or not to use CGFloat.

We're aware of this problem and consider it to be serious: we are evaluating several different solutions right now and will roll one out in a later beta. As you notice, you can cope with this today by casting to Double. This is inelegant but effective :-)

Upvotes: 3

Related Questions