This question already has answers here:
Swift: Nil is incompatible with return type String
(3个答案)
3年前关闭。
在Swift中,我有一个返回某种对象的函数。该对象是可选的。当它不存在时,我想我应该返回
它说:
但是我不想返回诸如空List对象之类的东西,当optional为空时,我不希望返回任何内容。怎么做?
或仅返回
您有几种选择:
返回可选列表(列表?) 未找到数据时返回一个空列表 返回一个异常(取决于上下文) 使用一个枚举来表示Either/Result(类似于Optional,但根据您的用例可能会更好)
(3个答案)
3年前关闭。
在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?
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]
}
您有几种选择: