Ryo
Ryo

Reputation: 15

Cannot convert return expression of type '()' to return type 'Double'

what's a a expression of type '()' ?

and this version is not correct

var compteEnBanque: Double = 999.5


func shopping(_ new: Double) -> Double {
    guard compteEnBanque >= new else {
        return compteEnBanque
    }
    return compteEnBanque -= new
}

error : Cannot convert return expression of type '()' to return type 'Double'

but this version is correct

    var compteEnBanque: Double = 999.5


func shopping(_ new: Double) -> Double {
    guard compteEnBanque >= new else {
        return compteEnBanque
    }
    return compteEnBanque - new
}

Sorry, I'm not english native and thanks for your help.

Upvotes: 0

Views: 7654

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

() is an empty tuple in Swift - which is also Void.

The -= operator returns Void, since it mutates the left-hand side operand rather than returning its new value.

You should first do -= and then return the value of the left-hand side operand to both update it and then return its new value.

var compteEnBanque: Double = 999.5


func shopping(_ new: Double) -> Double {
    guard compteEnBanque >= new else {
        return compteEnBanque
    }
    compteEnBanque -= new
    return compteEnBanque
}

Upvotes: 2

Related Questions