Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift type does not conform to protocol NilLiteralConvertible

Tags:

I have method:

func  getByEmail(email:String) -> MeeterAccount{    for  acct in accountsList  {      if  acct.getEmail().equalsIgnoreCase(email)  {     return acct;     } }   return nil; // here I get an error: type 'MeeterAccount' does not conform to protocol NilliteralConvertible } 

How to get rid of this error?

I thought to write something like that:

func  getByEmail(email:String) -> MeeterAccount{      var out:MeeterAccount!      for  acct in accountsList  {         if  acct.getEmail().equalsIgnoreCase(email)  {             out = acct         }     }     return out; } 

That doesn't throw this error. Sounds like Swift makes me write only 2nd way.

Why I can't return nil?

like image 953
snaggs Avatar asked Aug 15 '14 07:08

snaggs


1 Answers

If your function can return nil, then it should be declared as ... -> MeeterAccount? (an optional type). Then the caller knows that it can be nil. (Your second example works but would crash because return out will implicitly try to unwrap nil.)

like image 110
jtbandes Avatar answered Oct 21 '22 13:10

jtbandes