常量"soda1"推断为类型为"()",这可能是出乎意料的



只是一个简单的小代码。它确实运行并打印出正确的结果,但我收到错误:常量"soda1"推断为类型为"((",这可能是意外的。不知道如何解决它。尝试编写一个简单的程序来输出一升苏打水的价格。

func sodaoffer(type: String, price: Double, size: Double, amount: Double = 1) {
    let priceL = price / (size * amount)
    print("(type) costs (priceL) per liter")
}
let soda1 = sodaoffer(type: "Cola", price: 15, size: 1.5)
let soda2 = sodaoffer(type: "Fanta", price: 50, size: 0.5, amount: 4)
let soda3 = sodaoffer(type: "Faxe Kondi", price: 25, size: 2)

您正在为变量分配一个返回 (( 或 Void(这没有任何意义(的函数。

尝试返回一些东西:

func makeSodaOfferString(type: String, price: Double, size: Double, amount: Double = 1) -> String {
    let priceL = price / (size * amount)
    return "(type) costs (priceL) per liter)"
}
let sodaOffer1 = makeSodaOfferString(type: "Cola", price: 15, size: 1.5)
let sodaOffer2 = makeSodaOfferString(type: "Fanta", price: 50, size: 0.5, amount: 4)
let sodaOffer3 = makeSodaOfferString(type: "Faxe Kondi", price: 25, size: 2)
print(sodaOffer1)
print(sodaOffer2)
print(sodaOffer3)

最新更新