Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Compiler Error Int is not convertible to CGFloat

Im trying to run this code but the compiler is bugging me about Int can not convert to CGFloat, but I have never declare min, max or value as variables 'Int' nor mentioned them before.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */
    bird.physicsBody.velocity = CGVectorMake(0, 0)
    bird.physicsBody.applyImpulse(CGVectorMake(0, 8))   
}

func clamp (min: CGFloat, max: CGFloat, value:CGFloat) -> CGFloat {
    if (value > max) {
        return max
    } else if (value < min){
        return min
    }else{
        return value
    }
}

override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */

    bird.zRotation = self.clamp(-1, max: 0.5, value: bird.physicsBody.velocity.dy * (bird.physicsBody.velocity.dy < 0 ?0.003 : 0.001 ))

}

Compiler marks at '-1' the following 'Int' is not convertible to "CGFloat"

Please help

like image 371
Emanuel Gallardo Avatar asked Sep 11 '14 19:09

Emanuel Gallardo


1 Answers

Pass Int as parameter to CGFloat init:

var value = -1

var newVal = CGFloat(value)  // -1.0

In your case:

bird.zRotation = self.clamp(CGFloat(-1), max: 0.5, value: bird.physicsBody.velocity.dy * (bird.physicsBody.velocity.dy < 0 ?0.003 : 0.001 ))

Reference:

CGFloat:

struct CGFloat {

/// The native type used to store the CGFloat, which is Float on
/// 32-bit architectures and Double on 64-bit architectures.
typealias NativeType = Double
init()
init(_ value: Float)
init(_ value: Double)

/// The native value.
var native: NativeType
}

extension CGFloat : FloatingPointType {
    // ... 
    init(_ value: Int)  // < --- your case
    // ... 
}
like image 171
Maxim Shoustin Avatar answered Nov 07 '22 17:11

Maxim Shoustin