Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return nil in swift function [duplicate]

Tags:

swift

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?

like image 821
Evgeniy Kleban Avatar asked Jul 21 '17 05:07

Evgeniy Kleban


1 Answers

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:

  • Return optional List (List?)
  • Return an empty list when no data is found
  • Return an exception (depends on context)
  • Use an enum to represent Either/Result (similar to Optional but could be better depending on your use-case)
like image 125
nathan Avatar answered Nov 02 '22 18:11

nathan