What is the _ underscore before the Swift catch block?
Swift 2.0 added do {} catch {}
which can be used like this:
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(params, options: []);
} catch let jsonError as NSError {
print(jsonError);
}
but I also saw that in my 2.0 converted classes the catch is implemented with underscore:
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(params, options: []);
} catch _ {
}
which makes it especially confusing, why not just do something after the catch, which is perfectly valid code:
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(params, options: []);
} catch {
}
What is this underline _
, what can I do with it, how would I implement this in my own function signatures? I didn't use Swift 1.2 in the previous declaration NSError
, so it makes sense that the conversion throws an error, but why use it _
?
source to share
You are asking a question about automatic conversion. This is just a starting place! Apple doesn't know what you want to do, so they provide an absolutely minimal neutral blocking catch-catch - it doesn't do anything, but we compile because it has everything. Obviously, if you want to grab a variable error
, you delete _
and commit the variable error
. You might want to do a lot more for example. write a more targeted catch block. This is for you to build upon what is given to you.
source to share
If the variable declared before the catch block is not actually used in the next block, then Xcode will automatically convert it to _
as it is not used. So in your example above, if jsonError was not actually used in the catch block, Xcode can automatically convert that value to _
. This is not only for do {} catch {}
, but for things like if let ... { }
.
I guess because it does it with other things too, for example if let ... {}
if they didn't put _
in those places the code didn't actually work. Therefore, it is _
safe everywhere , although in some places you may not need it.
source to share