只是一个简单的小代码。它会运行,并打印出正确的结果,但我收到错误:Constant' 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)
答案 0 :(得分:3)
您正在为变量分配一个返回()或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)