iosswiftxcodeoption-typeswift-optionals

Getting a value of "Optional(<data value>)" even when unwrapping


I'm trying to initialize parameters for an Alamofire request. For some reason, the value for one of the parameters always ends up with a value of "Optional()", even when I'm unwrapping it.

Here is what I've tried...

var params : [String : Any] = [:]
    
params["facility_id"] = facility.facilityId ?? 0
if facility.email != nil {
    params["email"] = facility.email!
}
if let url = facility.facebookUrl {
    params["facebook_url"] = url
}

The value for params["facebook_url"] ends up as "Optional(Facebook.com)"

I've tried (just for testing)

params["facebook_url"] = facility.facebookUrl!

and I still get the word "Optional(" in my value.

How do I get the "Optional()" to go away?


Solution

  • When you access a dictionary it returns optional of it's value type because it doesn't know runtime whether certain key is available in the dictionary or not. If the key is present then it's value is returned but if it's not then we get nil value.

    Use optional binding to access unwrapped value:

    if let url = params["facebook_url"] {
        print(url) // facebook url
    }
    

    In case double optional unwrapping:

    if let urlOptional = params["facebook_url"], let value = urlOptional {
        print(value) // facebook url
    }
    

    Note: Also check the source where you have set the value of 'facebook_url' key.