gpt4 book ai didi

swift - 为什么可选属性必须返回一些东西?

转载 作者:可可西里 更新时间:2023-11-01 01:37:57 25 4
gpt4 key购买 nike

所以我有这个只读属性:

  private var allProducts: [String]? {
if let selectedProductSeries = selectedProductSeries {
return ["someProduct"]
} else {
return nil
}
}

很好,这就是我想要的,但我的问题是为什么我必须在我的 if/else 中详尽无遗。我将其标记为可选,因此我希望发生的情况是,如果我不返回任何东西,它就是 nil。但是当然,如​​果我去掉 else,它会提示说:Missing return in function expected to return: [String]? 这很有趣,因为消息说它 期待我返回一些东西,即使它是可选的。

这是为什么?

最佳答案

如果隐式添加了 return nil,我认为错误可能会更频繁地发生。在包含许多 ifswitch 语句的函数/方法内部,您很容易忽略,您可能会通过每条语句。明确的 return nil 会迫使您处理这种可能性。

关于swift - 为什么可选属性必须返回一些东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33552023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com