In Swift I have a function that returns some kind of object. That object is optional. When it does not exist, I suppose I should return nil
, but Swift forbid me to do so. Following code is not working:
func listForName (name: String) -> List {
if let list = listsDict[name] {
return list
} else {
return nil
}
}
It says : error: nil is incompatible with return type 'List'
But I don't want to return something like empty List object, I want to return nothing when optional is empty. How to do that?
To fix the error you need to return an Optional: List?
func listForName (name: String) -> List? {
if let list = listsDict[name] {
return list
} else {
return nil
}
}
Or just return listsDict[name]
since it will either be optional or have the list itself.
func listForName (name: String) -> List? {
return listsDict[name]
}
But i don't want to return something like empty List object, i want to return nothing when optional is empty. How to do that?
You have several choices:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With