FireDragonMule
FireDragonMule

Reputation: 1347

Convert CGFloat to NSNumber in Swift

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?

Upvotes: 34

Views: 20019

Answers (5)

Mark Leonard
Mark Leonard

Reputation: 2096

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)

Upvotes: 2

Tot FOURLEAF
Tot FOURLEAF

Reputation: 129

For Swift 3.1

var final_price: CGFloat = 12.34
let num = final_price as NSNumber

Upvotes: 11

ttarik
ttarik

Reputation: 3853

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))

Upvotes: 72

Narasimha Nallamsetty
Narasimha Nallamsetty

Reputation: 1263

For me this is worked.

self.configuration.cellHeight as NSNumber!

Upvotes: 1

Shiyan Xu
Shiyan Xu

Reputation: 1192

Swift 3

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

Upvotes: 7

Related Questions