【问题标题】:Return nil in swift function [duplicate]在 swift 函数中返回 nil [重复]
【发布时间】:2019-09-12 13:24:28
【问题描述】:

在 Swift 中,我有一个返回某种对象的函数。该对象是可选的。当它不存在时,我想我应该返回nil,但 Swift 禁止我这样做。以下代码不起作用:

func listForName (name: String) -> List {

        if let list = listsDict[name] {
            return list
        }   else {
            return nil
        } 
    }

上面写着:error: nil is incompatible with return type 'List'

但我不想返回空 List 对象之类的东西,当 optional 为空时我想什么都不返回。该怎么做?

【问题讨论】:

  • 这是因为返回类型List 不是可选的,通常将返回更改为List?
  • @CarpenterBlood 谢谢

标签: swift


【解决方案1】:

要修复错误,您需要返回一个 Optional:List?

func listForName (name: String) -> List? {

    if let list = listsDict[name] {
        return list
    }   else {
        return nil
    } 
}

或者只返回listsDict[name],因为它要么是可选的,要么有列表本身。

func listForName (name: String) -> List? {
    return listsDict[name]
}

但我不想返回空 List 对象之类的东西,当 optional 为空时我想什么都不返回。该怎么做?

您有多种选择:

  • 返回可选列表(List?)
  • 未找到数据时返回空列表
  • 返回异常(取决于上下文)
  • 使用枚举来表示 Either/Result(类似于 Optional,但根据您的用例可能会更好)

【讨论】:

  • 而正文可以简单地是return listsDict[name],这在很大程度上否定了函数的全部意义。
  • 虽然不是真正的骗子,他的问题是:i want to return nothing when optional is empty. How to do that?。如上所述,有几种方法可以做到这一点
猜你喜欢
  • 2019-10-12
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 2018-05-09
  • 1970-01-01
  • 1970-01-01
  • 2015-09-05
相关资源
最近更新 更多