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.
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.
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.
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))
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With