【问题标题】:How to return a value from an if let statement inside a function?如何从函数内的 if let 语句返回值?
【发布时间】:2021-03-27 01:16:31
【问题描述】:

我正在从官方的 Apple 课程书籍中自学 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 itemInStock(item: String) -> Int? {
    
    if let availableItems = stock[item] {
        switch availableItems {
        case 1...Int.max:
            print("\(item) are available: \(availableItems) items.")
            if let price = prices[item] {
                print("\(item) cost \(price) USD per item.")
                return Int(price)
            }
            
        default:
            print("Sorry, \(item) are out of stock")
            return nil
        }
    
    }
    return Int(price)
}

没有 -> Int?return 行它可以正常工作。 当我添加return Int(price)return nil 时,Xcode 给了我一个错误信息:“Missing return in function...”。

所以我最后添加了另一个return Int(price) 行。但是 Xcode 说它在范围内找不到它。

如何从if-let 语句中获取price 值?

即使我在函数内部声明了一个变量,然后在switch 内部使用price 设置它的新值,它仍然会在switch 外部具有其初始值。

似乎有一种非常简单的方法可以处理这些情况,但我在任何地方都找不到。我尝试使用不同的关键字进行搜索。

UPD 感谢 Joakim Danielson,我设法获得了更简洁的代码:

func itemInStock_V2(item: String) -> Double? {
    if let availableItems = stock[item], availableItems > 0 {
            print("\(item) are available: \(availableItems) items.\n\(item) cost \(String(describing: prices[item])) USD per item.")
            return prices[item]
        } else {
            print("Sorry, \(item) are out of stock")
            return nil
    }
}

我不知道可以在if let 声明之后添加另一个条件。

结果我的问题是我必须在代码的每个结果之后编写return命令,即使它永远不会发生。

【问题讨论】:

  • 你的函数应该返回一个双精度值,因为这是价格的类型,-> Double?。而且您根本不需要开关,而是将if let 扩展为另一个条件, availableItems > 0。然后你可以从 if 和 nil 之外返回价格。如果您在函数中使用局部变量,则将其初始化为 nil

标签: swift if-statement switch-statement return-value optional


【解决方案1】:

问题是,如果 if-let 语句不起作用,xcode 不知道返回什么,这应该会有所帮助:

func itemInStock(item: String) -> Int? {
    if let availableItems = stock[item] {
    
        switch availableItems {
        case 1...Int.max:
            print("\(item) are available: \(availableItems) items.")
            if let price = prices[item] {
                print("\(item) cost \(price) USD per item.")
                return Int(price)
            } else {
                // in case (if let price = prices[item]) didn't work
                return nil
            }
            
        default:
            print("Sorry, \(item) are out of stock")
            return nil
        }
        
    } else {
        // in case (if let availableItems = stock[item]) didn't work
        return nil
    }
} 

如果您想立即摆脱 return nil 语句,也可以使用 guard-let

【讨论】:

    【解决方案2】:

    这可能会有所帮助

    func itemCost(item: String) -> Double? {
        if let available = stock[item] {
            if available == 0 {
                // none available
                return nil
            } else {
                // return the price
                return prices[item]
            }
        } else {
            // unknown item
            return nil
        }
    }
    

    【讨论】:

      【解决方案3】:

      你只从 if 语句返回,从不返回。我想它一定是这样的:

      func itemInStock(item: String) -> Int? {
      
          if let availableItems = stock[item] {
              switch availableItems {
              case 1...Int.max:
                  print("\(item) are available: \(availableItems) items.")
                  if let price = prices[item] {
                      print("\(item) cost \(price) USD per item.")
                     return Int(price)
                 }
              default:
                  print("Sorry, \(item) are out of stock")
                  return nil
              }
      
          } else {
             return nil
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多