VAAA VAAA - 1 year ago 57
Swift Question

Swift - Remove double optional string from dictionary

This is breaking my head.

I have one dictionary:

var formSearchValues : Dictionary<String, Any?>

Then I call a function to send to server some data and for that I need to create extra dictionary for the params.

let lastName = String(formSearchValues["lastname"])
let firstName = String(formSearchValues["firstname"])

searchProvider(lastName, firstName: firstName)

Then I have my function searchProvider:

func searchProvider(lastName: String, firstName : String){

let params = [
"lastname": fathersLast == "" ? NSNull() : fathersLast,
"firstname": NSNull(),
"email" : state.userEmail,
"male": false,
"female": false,
"taxid": NSNull(),
] as Dictionary<String, AnyObject>

// print params

// make call to server


When I print my params I see:

"lastname": Optional(Optional("Smith"))

And of course on my server the search won't work because of that.

Any clue on how to remove this annoying Optional strings?

Answer Source

As @Eric D suggested, the problem is related to how you extract values from your dictionary.

Solution 1

Replace this

let lastName = String(formSearchValues["lastname"])
let firstName = String(formSearchValues["firstname"])

with this

guard let
        firstName = formSearchValues["firstName"] as? String,
        lastName = formSearchValues["lastName"] as? String
        else { fatalError() }

Please note that this code will crash your app if valid Strings are not found for the firstName and lastName. Alternatively you can replace the fatalError() instruction with another flow-breaking instruction like return.

Solution 2

If you have a default value for when firstName or lastName are nils then here's the code

let defaultValue = ""
let firstName = (formSearchValues["firstName"] as? String) ?? defaultValue
let lastName = (formSearchValues["lastName"] as? String) ?? defaultValue