Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Function generates unecessary type conversion in Swift #83

Open
crmorello opened this issue Mar 30, 2023 · 0 comments
Open

Function generates unecessary type conversion in Swift #83

crmorello opened this issue Mar 30, 2023 · 0 comments
Assignees

Comments

@crmorello
Copy link

This is not a big issue and probably doesn't need a fix, but I thought I would point it out. It's coercing the Float to a Double because the hardcoded values are seen as Doubles, but I feel like it should be flipped and instead infer the hardcoded values as Floats.

This cito function

public static float celsiusToFahrenheit(float value) => (1.8 * value) + 32.0;

Translates to Swift with a type conversion to Double and then back to Float

public static func celsiusToFahrenheit(_ value : Float) -> Float
{
    return Float(1.8 * Double(value) + 32.0)
}

Now if I specify the types and store the multiplier and addition in a variable it behaves

public static float celsiusToFahrenheit(float value) {
    float multiplier = 1.8;
    float add = 32.0;
    return (multiplier * value) + add;
}

Output:

public static func celsiusToFahrenheit(_ value : Float) -> Float
{
    let multiplier : Float = 1.8
    let add : Float = 32.0
    return multiplier * value + add
}

So I assume all "harcoded" Floats are seen as Doubles when it generates the code. Swift itself can have issues with this, but only when it infers the type on a variable. Hardcoded values in general get inferred to have the type of what's around it, but it is true that the default/inferred type for hardcoded values is a Double in Swift so I can see why it generates the way it does.

let a = 32.0 // infers as a double
let b: Float = 32.0

let c = a + b // compile error due to a being a double
let d = b + 32.0 // infers as a float

The only issue for me is I don't really need the extra precision and it's double the size (8 byte vs a 4 byte).
So again, no fix needed, but might be nice in the future to have hardcoded number values infer the type of surrounding variables.

@pfusik pfusik self-assigned this Jun 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants