Handling errors
If we try to call a function, such as normal, Swift is going to give us an error, as shown in the following example:
let repeated1 = repeatString("Hello", untilLongerThan: 20) // Error: Call can throw but is not market with 'try'
To eliminate this error, we must add the try
keyword before the call. However, before we move forward, I would recommend that you wrap all of your code inside a function, if you are following along in a playground. This is because throwing errors at the root level of a playground will not be handled properly and may even cause the playground to stop working. To wrap your code in a function, you can simply add the following code:
func main() { // The rest of your playground code } main()
This defines a function ...
Get Swift: Developing iOS Applications now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.