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

11 views
Skip to first unread message

Raki iOS Dev

unread,
Dec 11, 2015, 9:03:32 PM12/11/15
to iphonesdkd...@googlegroups.com

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.

Please let me know how can I fix this.


Regards,
Rakesh.Y,
iOSDeveloper,
Bangalore,India.
http://beginnersiosdev.blogspot.com/

Jesse Tayler

unread,
Dec 12, 2015, 12:02:07 AM12/12/15
to iphonesdkd...@googlegroups.com
causes what crash?

--
You received this message because you are subscribed to the Google Groups "iPhone SDK Development" group.
To unsubscribe from this group and stop receiving emails from it, send an email to iphonesdkdevelop...@googlegroups.com.
To post to this group, send email to iphonesdkd...@googlegroups.com.
Visit this group at https://groups.google.com/group/iphonesdkdevelopment.
For more options, visit https://groups.google.com/d/optout.

Raki iOS Dev

unread,
Dec 12, 2015, 1:43:37 AM12/12/15
to iphonesdkd...@googlegroups.com
Fixed it by 

Nil Coalescing Operator

let str = address?.firstName ?? ""

Regards,
Rakesh.Y,
iOSDeveloper,
Bangalore,India.
http://beginnersiosdev.blogspot.com/

Reply all
Reply to author
Forward
0 new messages