Rakesh iOS Dev
Rakesh iOS Dev

Reputation: 955

How to check nil for Swift Optionals with out unwrap it?

I knew that safely unwrapping is as follows

var firstName:String?

if let firstName = firstName
{
    dictionary.setObject(firstName, forKey: "firstName")
}
else 
{
    dictionary.setObject("", forKey: "firstName")
}

I want to add firstname to dictionary even it is nil also. I will have 10-15 var's in dictionary. I do not want to check for this condition 10-15 times for ear var. I am having more than 1000 optionals through out project.

So thought of writing writing a func will help me duplicate the code and reduce the number of lines. So implemented this func as below.

func checkNull(str:String) -> String
{
    return str.characters.count > 0 ? "\(str)" : ""
}

but while calling the func,

let addressstr = self.checkNull(address?.firstName)

firstname is the var in address model here. The auto correction sugguests

let addressstr = self.checkNull((address?.firstName)!)

The above line causes the crash.

Upvotes: 0

Views: 965

Answers (1)

Qbyte
Qbyte

Reputation: 13283

First of all firstName is an Optional therefore you cannot pass it to a function which only takes String.

In addition this line:

str.characters.count > 0 ? "\(str)" : ""

Is equivalent to just returning str so you don't check whether it is an Optional.

Solution

In this case it is way easier to use the nil coalescing operator:

let addressstr = address?.firstName ?? ""

If address is not nil firstName gets unwrapped and bind to addressstr. Otherwise this string gets assigned to it: ""

Upvotes: 3

Related Questions