Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can use CGFloat in Swift?

Tags:

var posinonY:Float = Float(y) + Float(pipeDown.size.height) + Float(verticalPipeGap)
pipeDown.position = CGPointMake(0.0, Float(posinonY))

I get this error:

"NSNumber' is not a subtype of 'CGFloat'"

Why?


Edit:

CGFLoat need double type

pipeDown.position = CGPointMake(0.0,  Double(posinonY))

this is ok.

like image 733
Aeli.li Avatar asked Jun 03 '14 07:06

Aeli.li


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.

How swift 5.5 and onwards allows us to use CGFloat and Double interchangeably?

Available from Swift 5.5 SE-0307 introduced a small but important quality of life improvement: Swift is able to implicitly convert between CGFloat and Double in most places where it is needed. Swift implements this by inserting an implicit initializer as needed, and it will always prefer Double if it's possible.

How do you round up a number in Swift?

Rounding Numbers in SwiftBy using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

Is CGFloat Double or Float?

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


2 Answers

Use CGFloat(number) instead of Float(number)

pipeDown.position = CGPointMake(0.0, CGFloat(posinonY))
like image 194
MJN Avatar answered Sep 20 '22 06:09

MJN


Since CGFloat is not a Double on 32bit, it becomes hard to use CGGeometry and frameworks like CoreGraphics or SpriteKit. This library makes it a little easier and hopefully Apple takes care of it soon.

I wrote this to help out https://github.com/seivan/ScalarArithmetic

But if you want to just make it work without dependencies use var myFloat:CGFloat explicitly, and make sure to cast any Double (numbers that are type inferred) to CGFloat 2.0 is inferred to be a Double and won't play along with the CG-Structs on 32bit.

like image 23
Seivan Avatar answered Sep 19 '22 06:09

Seivan