johnniexo88 johnniexo88 - 1 year ago 247
Swift Question

Swift string construction was too complex to be solved in reasonable time

Here is my code:

let request = NSMutableURLRequest(URL: NSURL(string: "")!)
request.HTTPMethod = "POST"
let postString = "user_name="+user_name+"&first_name="+first_name.text+"&last_name="+last_name.text+"&company_name="+company_name.text+"&location="+location.text+"&phone="+phone.text+"&website="+website.text+"&email="+email.text+"&about="+about.text
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")

when I try to run the app, it gives me the following error on

Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions

Answer Source

Try this:

let parameters = ["user_name" : user_name,
    "first_name" : first_name.text,
    "last_name" : last_name.text,
    "company_name" : company_name.text,
    "location" : location.text,
    "phone" : phone.text,
    "website" : website.text,
    "email" : email.text,
    "about" : about.text].map { "\($0)=\($1 ?? "")" }
let postString = parameters.joinWithSeparator("&")

The solution will first create a dictionary with the parameters and their values (this will also improve readability and maintainability of your code).

Then it will execute a "map" on that dictionary, turning it into an array of strings containing key=value (and if since text on UITextField is optional it will set it to an empty string if it's nil).

Lastly it will create a string by joining all strings in the array with the separator &

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download