Grayson Pike
Grayson Pike

Reputation: 397

CGFloat cannot be initialized with Float

I have a function that I have written for a Sprite Kit application using Swift. Xcode currently errors on building, claiming that a CGFloat() cannot be initialized. Here is my code:

func someFunction () {
    var x:Float = 5.0
    return CGFloat(x)
}

Which throws the error:

"Could not find an overload for 'init' that accepts the supplied arguments"

After command clicking on CGFloat, I can see inits with Floats, Doubles, and Ints for possible parameters.

The following code also creates the same error

func someFunction () {
    return CGFloat(5.0)
}

as well as

func someFunction () {
    return 5;
}

which gave the error

"Type '()' does not conform to protocol 'IntegerLiteralConvertible'"

I feel that I am obviously missing some core concept of the language that is affecting the way my code behaves.

Upvotes: 3

Views: 1641

Answers (1)

Daniel K
Daniel K

Reputation: 1129

The concept that you are apparently missing is that you did not declare a return Type for your functions.

It should be

func someFunction () -> CGFloat {
    var x:Float = 5.0
    return CGFloat(x)
}

This declares that someFunction is returning a value of type CGFloat.

Upvotes: 4

Related Questions