Raul Gonzalez
Raul Gonzalez

Reputation: 875

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

Upvotes: 8

Views: 9106

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

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
    // ... 
}

Upvotes: 16

Related Questions