我正在研读苹果的应用程序开发与Swift的书,我一直有一些问题的选项部分。
在访问另一个字典以返回满足条件的可选值后,我将无法访问字典。返回的错误是:
函数中缺少返回值,期望返回“双?”
var prices = ["Chips": 2.99, "Donuts": 1.89, "Juice": 3.99, "Apple": 0.50, "Banana": 0.25, "Broccoli": 0.99]
var stock = ["Chips": 4, "Donuts": 0, "Juice": 12, "Apple": 6, "Banana": 6, "Broccoli": 3]
func priceCheck(name: String) -> Double? {
let pricefinder = name
if let name = stock[name] {
print(name)
if name > 0 {
if let pricefinder = prices[pricefinder] {
print(pricefinder)
return pricefinder
} else {
return nil
}
}
} else {
return nil
}
}上面的代码哪里出错了?我需要检查一个产品是否有库存,然后返回它的价格,如果该条件评估为真。
还有更优雅的解决方案吗?
发布于 2018-02-10 16:16:35
通过利用Swift提供的一些工具,您的功能可以缩短很多。来,看看,这也是一样的.
func priceCheck(name: String) -> Double? {
guard let stockAmount = stock[name],
stockAmount > 0,
let price = prices[name] else {
return nil
}
return price
}发布于 2018-02-10 16:04:08
问题只是你没有涵盖你的逻辑中的所有情况。如果name不大于零呢?您的代码没有说明该做什么。因此,在这种情况下无法返回值:
func priceCheck(name: String) -> Double? {
let pricefinder = name
if let name = stock[name] {
print(name)
if name > 0 {
if let pricefinder = prices[pricefinder] {
print(pricefinder)
return pricefinder
} else {
return nil
}
} else { // this is the question: what if it isn't?
return nil // ???? I don't know what you want to do...
// ... but you MUST return something in this situation
}
} else {
return nil
}
}听编译器的话。它知道的比你多。
发布于 2018-02-10 16:04:18
作为一个非常快速的解决方案,您所要做的就是在函数的末尾添加return nil:
func priceCheck(name: String) -> Double? {
let pricefinder = name
if let name = stock[name] {
print(name)
if name > 0 {
if let pricefinder = prices[pricefinder] {
print(pricefinder)
return pricefinder
} else {
return nil
}
}
} else {
return nil
}
// here we go:
return nil
}因为在某个点(name不大于0),函数不返回任何内容。
另外,请注意,您可以将您的函数-as实现为更短的版本,如:
func priceCheck(name: String) -> Double? {
let pricefinder = name
if let name = stock[name], name > 0 {
if let pricefinder = prices[pricefinder] {
return pricefinder
}
}
return nil
}如果函数在其末尾返回零,则没有必要为每个else { return nil }添加if;或者您甚至可以使用guard语句来实现Fogmeister`s answer中提到的。
https://stackoverflow.com/questions/48722681
复制相似问题