Book Image

Learning Swift Second Edition - Second Edition

By : Andrew J Wagner
Book Image

Learning Swift Second Edition - Second Edition

By: Andrew J Wagner

Overview of this book

Swift is Apple’s new programming language and the future of iOS and OS X app development. It is a high-performance language that feels like a modern scripting language. On the surface, Swift is easy to jump into, but it has complex underpinnings that are critical to becoming proficient at turning an idea into reality. This book is an approachable, step-by-step introduction into programming with Swift for everyone. It begins by giving you an overview of the key features through practical examples and progresses to more advanced topics that help differentiate the proficient developers from the mediocre ones. It covers important concepts such as Variables, Optionals, Closures, Generics, and Memory Management. Mixed in with those concepts, it also helps you learn the art of programming such as maintainability, useful design patterns, and resources to further your knowledge. This all culminates in writing a basic iOS app that will get you well on your way to turning your own app ideas into reality.
Table of Contents (19 chapters)
Learning Swift Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

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 called main that contains all the normal playground code that is called once, at the end of the playground.

Now, let's get back to using the try keyword. There are actually three forms of it: try, try?, and try!. Let's start by discussing the exclamation...