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

Scope


Scope is all about which code has access to which other pieces of code. Swift makes it relatively easy to understand because all scope is defined by curly brackets ({}). Essentially, code in curly brackets can only access other code in the same curly brackets.

How scope is defined

To illustrate scope, let's look at some simple code:

var outer = "Hello"
if outer == "Hello" {
    var inner = "World"
    print(outer)
    print(inner)
}
print(outer)
print(inner) // Error: Use of unresolved identifier 'inner'

As you can see, outer can be accessed from both in and out of the if statement. However, since inner was defined in the curly brackets of the if statement, it cannot be accessed from outside of them. This is true of structs, classes, loops, functions, and any other structure that involves curly brackets. Everything that is not in curly brackets is considered to be at global scope, meaning that anything can access it.

Nested types

Sometimes, it is useful to control scope yourself. To do...