Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 980
FireDragonMule Avatar asked Dec 15 '15 00:12

FireDragonMule


People also ask

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.

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 NSNumber in Swift?

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 .


2 Answers

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)) 
like image 174
3 revs, 3 users 51% Avatar answered Sep 21 '22 18:09

3 revs, 3 users 51%


For Swift 3.1

var final_price: CGFloat = 12.34 let num = final_price as NSNumber 
like image 43
Tot FOURLEAF Avatar answered Sep 22 '22 18:09

Tot FOURLEAF