Reputation: 329
I my program have multiple do-try-catch
clause but I'm using the same catch
function all through out, how can I factor it out?
E.g
func tryCatch1 {
do{
try something.save
}catch let error as UserError{
print(error.description)
}
}
// Another try catch
func tryCatch2 {
do{
try somethingAgain.save
}catch let error as UserError{
print(error.description)
}
}
Is it possible to create something like "universal catch"
Upvotes: 0
Views: 77
Reputation: 70113
If you find yourself typing the same boilerplate code again and again, you may want to create an Xcode "Code Snippet" that you call with a simple sequence of characters.
In Xcode, open the right-side "Utilities" panel (you can use the last of the three little square icons at the upper-right for that).
In the lower part there's the section where you usually pick the UI objects: click on the { }
icon, named "Show the code snippet library". you can now see a list of premade snippets.
To make yours, select your code in Xcode with the mouse, complete with the indentation:
do {
} catch let error as UserError {
print(error.description)
}
Then drag the selected code to the snippets section (you can hold the ALT (option) key when dragging for a visual help).
The snippets section highlight: drop the selection, it creates a new snippet at the bottom.
Click on it, click on edit: make your own title, description, shortcut, etc.
Now everytime in your code, at the chosen scope, when you type the shortcut, it is replaced by the snippet.
If my snippet has a shortcut of "dtc" (just an example, choose something that will not interfere will your code or Swift keywords), I just have to type "dtc" and "dtc" is replaced by the whole Do-Try-Catch block from the snippets.
Upvotes: 1