这是我的代码:
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.example.com/submit.php")!)
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)")
}
task.resume()
当我尝试运行该应用程序时,它在 postString
上出现以下错误:
Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
最佳答案
试试这个:
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("&")
该解决方案将首先创建一个包含参数及其值的字典(这也将提高代码的可读性和可维护性)。
然后它将在该字典上执行“映射”,将其转换为包含 key=value
的字符串数组(如果从 UITextField 上的
是可选的,如果为零,它会将其设置为空字符串)。text
最后,它将通过使用分隔符 &
连接数组中的所有字符串来创建一个字符串
关于Swift 字符串构造过于复杂,无法在合理的时间内解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38311459/