Swift: Extra argument 'error' in call
With Swift 2, the signature for NSJSONSerialization
has changed, to conform to the new error handling system.
Here's an example of how to use it:
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
With Swift 3, the name of NSJSONSerialization
and its methods have changed, according to the Swift API Design Guidelines.
Here's the same example:
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
SwiftUI: Random Extra argument in call error
try making a Group { } around your views. just 10 are allowed in Swiftui...with group you can add more. or use subviews...(would be cleaner code too)
Swift - Extra Argument in call
In some cases, "Extra argument in call" is given even if the call looks right, if the types of the arguments don't match that of the function declaration. From your question, it looks like you're trying to call an instance method as a class method, which I've found to be one of those cases. For example, this code gives the exact same error:
class Foo {
func name(a:Int, b: Int) -> String {
return ""
}
}
class Bar : Foo {
init() {
super.init()
Foo.name(1, b: 2)
}
}
You can solve this in your code by changing your declaration of setCity to be class func setCity(...)
(mentioned in the comments); this will allow the ViewController.setCity
call to work as expected, but I'm guessing that you want setCity
to be an instance method since it appears to modify instance state. You probably want to get an instance to your ViewController class and use that to call the setCity method. Illustrated using the code example above, we can change Bar as such:
class Bar : Foo {
init() {
super.init()
let foo = Foo()
foo.name(1, b: 2)
}
}
Voila, no more error.
Extra argument 'error' in call in swift
In Swift 2.0, you cannot add 'error' argument in NSJSONSerialization method, you need to use try-catch statement as follows:
func geocodeAddress(address: String!, withCompletionHandler completionHandler: ((status: String, success: Bool) -> Void)) {
if let lookupAddress = address {
var geocodeURLString = baseURLGeocode + "address=" + lookupAddress
geocodeURLString = geocodeURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let geocodeURL = NSURL(string: geocodeURLString)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let geocodingResultsData = NSData(contentsOfURL: geocodeURL!)
let request = NSMutableURLRequest(URL: geocodeURL!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
(let data, let response, let error) in
if let _ = response as? NSHTTPURLResponse {
do {
let dictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if error != nil {
print("error=\(error!)")
return
}
if let parseJSON = dictionary {
let status = dictionary["status"] as! String
if status == "OK" {
let allResults = dictionary["results"] as! Array<Dictionary<NSObject, AnyObject>>
self.lookupAddressResults = allResults[0]
// Keep the most important values.
self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"] as! String
let geometry = self.lookupAddressResults["geometry"] as! Dictionary<NSObject, AnyObject>
self.fetchedAddressLongitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lng"] as! NSNumber).doubleValue
self.fetchedAddressLatitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lat"] as! NSNumber).doubleValue
completionHandler(status: status, success: true)
}
else {
completionHandler(status: status, success: false)
}
}
} catch {
print(error)
}
}
}
task.resume()
})
}
}
Extra argument 'error' in call
Change
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
With
let urlData = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
And change
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
With
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as! NSDictionary
And your complete code will be:
let url:NSURL = NSURL(string: "http://userregistration.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let reponseError: NSError?
var response: NSURLResponse?
do {
let urlData = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as! NSDictionary
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1)
{
NSLog("Sign Up SUCCESS");
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"
}
let alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = error_msg as String
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
} else {
let alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
}
Extra argument in call when I call struct 11 times but not 10 times or lower
The closure that HStack
(and many other views) accept is a kind of function builder called ViewBuilder
. It only supports up to 10 View
s as arguments. These are all hardcoded in the SwiftUI module:
static func buildBlock<C0, C1, C2, C3, C4, C5, C6, C7, C8, C9>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6, _ c7: C7, _ c8: C8, _ c9: C9) -> TupleView<(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9)> where C0 : View, C1 : View, C2 : View, C3 : View, C4 : View, C5 : View, C6 : View, C7 : View, C8 : View, C9 : View
The designers could hardcode more, but decided not to. This is probably because you can simplify your view's code to not need to put that many views in a view builder.
In this case, you can use a ForEach
:
HStack {
ForEach(0..<11) { i in
BarView(barGradeValue: i, barSendValue: i < 6 ? (i + 1) * 10 : (11 - i) * 10, barFlashValue: 10)
}
}
Related Topics
Update Badge With Push Notification While App in Background
Scrolling Issue on Position Fixed Element on Ios
How to Clear the Entered Textfield When the User Taps on the Button
Force View Controller to Reload to Refresh Uiappearance Changes
Check If There Is an Emoji Contained in a String
How to Use Timer (Formerly Nstimer) in Swift
The Best Way to Remove Duplicate Values from Nsmutablearray in Objective-C
Uploading File With Parameters Using Alamofire
Background Location Services Not Working in iOS 7
Wait For Firebase to Load Before Returning from a Function
Sending an Http Post Request on Ios
How to Add Nsapptransportsecurity to My Info.Plist File
Understanding Ibeacon Distancing
How to Deploy an Iphone Application from Xcode to a Real Iphone Device
Creating a Segue Programmatically
How to Set the Cookies to Be Used by a Wkwebview
How to Determine the Content Size of a Uiwebview
Is [Uiscreen Mainscreen].Bounds.Size Becoming Orientation-Dependent in Ios8