34

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?

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
FireDragonMule
  • 1,347
  • 2
  • 16
  • 27

5 Answers5

72

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))
Himanshu A Jadav
  • 2,286
  • 22
  • 34
ttarik
  • 3,824
  • 1
  • 32
  • 51
  • 1
    the problem with let myNumber = NSNumber(value: Float(myFloat)) is that I lose precision CGFloat 0.4 => Float 0.400000006 – CiNN Oct 13 '16 at 10:25
11

For Swift 3.1

var final_price: CGFloat = 12.34
let num = final_price as NSNumber
Tot FOURLEAF
  • 129
  • 1
  • 2
7

Swift 3

let myNumber = NSNumber(value: Float(myCGFloat))

Raymond
  • 1,172
  • 16
  • 20
2

You can access a CGFloat's NativeType via the native property:

public var native: CGFloat.NativeType

The native type used to store the CGFloat, which is Float on 32-bit architectures and Double on 64-bit architectures.

With this you can create an NSNumber like so:

NSNumber(value: cgFloat.native)
Mark Leonard
  • 2,056
  • 19
  • 28
  • This should be the correct answer! By using `Float(cgFloat)` you may be loosing precision if the native type is a `Double`. `NSNumber(value: cgFloat.native)` is the way to go – OscarVGG Jun 19 '20 at 07:53
1

For me this is worked.

self.configuration.cellHeight as NSNumber!
Narasimha Nallamsetty
  • 1,215
  • 14
  • 16