Search code examples
swiftfloating-pointoption-type

Initializer for conditional binding must have Optional type, not 'Float' Error in swift


Given:

var conv_factor: String?
var standard_rate_in_usd: Double?

now I need a Float value

var floatVal: Float?

if let priceVal = Float(indexData.standard_rate_in_usd!),
   let convVal = Float((conversion_factor?.conv_factor)!) {
     floatVal = (priceVal * convVal)
}

then error: how to fix and get final value in float

Initializer for conditional binding must have Optional type, not 'Float'


Solution

  • There's a pretty random mix of force unwrapping and conditional wrapping here, so it's not really clear what it is you're trying to achieve.

    If you're asserting that none of these values can be nil and you're going to force unwrap in some parts, then just force unwrap it all. A construct like a?.b! doesn't make any sense. Just do a!.b (assuming b itself is non-optional).

    If you're going down the "dangerous" route, than it might look like:

    let floatVal = Float(indexData.standard_rate_in_usd * conversion_factor!.conv_factor)
    

    If you want to do conditional binding instead, then it would make sense to do:

    let floatVal: Float
    
    if let price = indexData.standard_rate_in_usd,
       let conversionFactorString = conversion_factor?.conv_factor,
       let conversionFactor = Float(conversionFactorString) {
        floatVal = Float(price) * conversionFactor)
    } else {
        // TODO: decide what the fallback behaviour should be
    }