我哪里出错了?前两行是错误所在.....调用中的额外参数“错误”
Posted
技术标签:
【中文标题】我哪里出错了?前两行是错误所在.....调用中的额外参数“错误”【英文标题】:does anyone know where i am going wrong? the first 2 lines is where the error is..... Extra argument 'error' in call有谁知道 【发布时间】:2016-03-18 18:26:26 【问题描述】:这是我遇到错误的代码:
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
if let parseJSON = json
let userId = parseJSON["userID"] as? String
if(userId != nil)
else
//display alert message
let userId = parseJSON["message"] as? String
var myAlert = UIAlertController(title: "Problem", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
谁能告诉我粗体字有什么问题?
【问题讨论】:
您在哪一行得到错误? (不要试图使您的代码的一部分粗体,因为这只会弄乱格式。)您到底遇到了什么错误?从 Xcode 的问题导航器中复制它并将其粘贴到您的问题中。 如果您告诉我们原因或您认为它出错的原因会有所帮助。 这是我收到错误的行:var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary 调用中的额外参数“错误” 【参考方案1】:您可能复制了一些为 Swift 1.x 编写的示例代码。
在 Swift 2.x 中,大多数 API 中的 error
参数被 Swift 的原生错误处理所取代。改写成这样:
do
var json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? NSDictionary
catch
// Handle error here
print("Error: \(error)")
【讨论】:
【参考方案2】:需要删除error参数并用try处理错误:
do
let object:AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
catch let caught as ErrorType
completeWith(nil, response, caught)
【讨论】:
【参考方案3】:在 Swift 中,JSONObjectWithData
不接受 error
参数。它会引发错误。
func f(data: NSData)
do
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
guard let parseJSON = json as? NSDictionary else
print("JSON wasn't an object")
return
guard let userId = parseJSON["userID"] as? String else
print("userId absent or not a string")
return
print("got userId \(userId)")
catch
print("Could not parse data as JSON: \(error)")
【讨论】:
我应该去掉什么代码来替换它?你能写出我需要输入的内容吗 您可以使用我发布的代码作为模板,并将打印语句替换为您的应用实际需要执行的任何操作(例如显示警报视图或其他)。以上是关于我哪里出错了?前两行是错误所在.....调用中的额外参数“错误”的主要内容,如果未能解决你的问题,请参考以下文章
用Excel使用VBA时显示运行错误5,错误调用参数,程序特别简单,如图,求问哪里出错了