Skip to content

Function generates unecessary type conversion in Swift #83

@crmorello

Description

@crmorello

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.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions