Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert CGFloat to CFloat in Swift

Tags:

swift

I'm simply trying to round the CGFloat return value of CGRectGetWidth.

override func layoutSubviews()  {
    let roundedWidth = roundf(CGRectGetWidth(self.bounds))
    ...
}

The compiler won't let me, giving the error:

'NSNumber' is not a subtype of 'CFloat'.

I guess there is some basic thing I am missing here. roundf is taking a CFloat as argument, so how can I convert my CGFloat to CFloat to make the conversion?

Update:

Now using round instead of roundf but I am still getting the same error. I've tried cleaning the project and restarting Xcode.

enter image description here

like image 802
Anton Avatar asked Jun 03 '14 10:06

Anton


People also ask

What is the difference between CGFloat and Float?

The Float and CGFloat data types sound so similar you might think they were identical, but they aren't: CGFloat is flexible in that its precision adapts to the type of device it's running on, whereas Float is always a fixed precision.

What is CGFloat in Swift?

Swift version: 5.6. A CGFloat is a specialized form of Float that holds either 32-bits of data or 64-bits of data depending on the platform. The CG tells you it's part of Core Graphics, and it's found throughout UIKit, Core Graphics, Sprite Kit and many other iOS libraries.


2 Answers

CGRect members are CGFloats, which, despite their name, are actually CDoubles. Thus, you need to use round(), not roundf()

override func layoutSubviews()  {
    let roundedWidth = round(CGRectGetWidth(self.bounds))
    ...
}
like image 136
Ben Gottlieb Avatar answered Sep 30 '22 18:09

Ben Gottlieb


The problem is that CGFloat is platform dependent (just like it is in ObjC). In a 32 bit environment, CGFloat is type aliased to CFloat - in a 64 bit environment, to CDouble. In ObjC, without the more pedantic warnings in place, round was happy to consume your float, and roundf your doubles.

Swift doesn't allow implicit type conversions.

Try building for an iPhone 5 and a iPhone 5s simulator, I suspect you'll see some differences.

like image 33
Jerry Jones Avatar answered Sep 30 '22 17:09

Jerry Jones