I have an extension in Swift that holds some properties which are CGFloat
's. The problem is that I don't know how to get the store the CGFloat
value as a NSNumber
using the associated objects
Here is the code I have that doesn't work but it details what I want to do:
var scaledFontSize: CGFloat { get { guard let fontSize = objc_getAssociatedObject(self, &AssociatedKeys.scaledFontSize) as? NSNumber else { //Set it let scaledFont:CGFloat = VGSizeValues.getValueFromValue(self.font.pointSize); //Fails here objc_setAssociatedObject(self,&AssociatedKeys.scaledFontSize, NSNumber( scaledFont),objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return scaledFont; } return CGFloat(fontSize.doubleValue); } }
Does anyone way to work around this?
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.
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.
NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .
In Swift 3.0
let myFloat : CGFloat = 1234.5 let myNumber = NSNumber(value: Float(myFloat))
or
let myNumber = NSNumber(value: Double(myFloat))
In Swift 2
let myNumber = NSNumber(double: myFloat.native)
or
let myNumber = NSNumber(double: Double(myFloat))
or
let myNumber = NSNumber(float: Float(myFloat))
For Swift 3.1
var final_price: CGFloat = 12.34 let num = final_price as NSNumber
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