Swift 字符串构造过于复杂,无法在合理的时间内解决

标签 swift xcode

这是我的代码:

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/

相关文章:

ios - WkWebview contentOffset 在设置动画 false 时不起作用

ios - 在第二次调用期间将数据填充到方法中的字典时出错

Swift 等效于 C++ 指针/引用约定?

ios - PDFView 无法调整大小

ios - Xcode 8.0 beta 找不到这样的模块 Alamofire Swift 3.0

objective-c - 使用 XCode4 中的文件夹引用自动包含/编译源代码

swift - CollectionView,两个按钮无法通信 - Swift 4

xcode - 导入 Alamofire 3.4 - 没有这样的模块 'Alamofire'

swift - 字符串插值。打印 String 数组的单个项目

ios - 随机化太空游戏 PowerUp 生成