
Swift By Example
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
Book DescriptionThis book is intended for those who want to learn to develop apps in Swift the right way. Whether you are an expert Objective-C programmer or new to this platform, you'll learn quickly, grasping the code of real-world apps to use Swift effectively. Prior experience in development for Apple devices would be helpful, but is not mandatory.What you will learn
Explore the features of Swift
Connect to a server and parse JSON data
Take advantage of CocoaPods to use thirdparty libraries
Utilize a clean and effective architecture to decrease complexity and speed up development
Work with the most useful parts of the iOS SDK
Build video games with SpriteKit and SceneKit
Develop apps from start to finish
Implement a weather app using fake data
Who this book is for
All prices
More details
Other editions
Additional editions

Person
Giordano Scalzo is a developer with 20 years of programming experience, since the days of ZX Spectrum. He has worked in Swift, Objective-C, C/C++, Java, .Net, Ruby, Python, and in a ton of other languages that he has forgotten the names of. After years of backend development, over the past 10 years, Giordano has developed extensively for iOS, releasing more than 20 apps-apps that he wrote for clients, enterprise applications, or on his own. He is currently a Tech Lead Consultant in London, where he leads mobile digital transformations through his company, Effective Code Ltd.
Content
Welcome to the World of Swift
A memory Game in Swift
A ToDoList in Swift
A Pretty Weather App
Flappy Swift
Polishing Flappy Swift
Cube Runner
Completing Cube Runner
Chapter 1. Welcome to the World of Swift
Swift is a language so new that even most programming experts have barely a few months of experience in it. However, it borrows most of its features from several other programming languages, such as Ruby, Python Scala, Rust, Groovy, and even JavaScript and Haskell. So, anyone who approaches Swift will already feel at home, recognizing the patterns and features of their favorite programming languages.
Moreover, unlike Objective-C, whose learning curve is really steep for beginners, Swift is really friendly for newcomers, who can write code once they learn the basics of the language.
Nevertheless, mastering Swift when using its more advanced features, such as effectively integrating patterns of functional programming with object-oriented concepts, takes time, and most best practices still need to be discovered.
Also, Swift's language is just one part of the story. A lone language without an environment where it can build something is just a sterile exercise. Swift is not a general-purpose language, but a language with a specific goal-building apps for iOS and OS X using the Cocoa framework.
It's in this framework that the complexity resides; Cocoa is a very big framework, with thousands of APIs and different patterns and best practices. It has changed significantly over the course of its several releases, for example, moving from the delegate pattern to the use of blocks to make components interact with loose coupling.
More than knowing the language, the real challenge is in knowing the framework. I want to stress that the aim of this chapter is just to help you get the first grasp of what Swift's constructs look like, and not to be exhaustive, so expect to find a certain degree of simplification. Also, be aware that a deeper knowledge of the language can be achieved with books that specialize only in Swift learning, whereas the goal of this book is to teach you how to build apps using Swift.
The first look at Swift
The most obvious way to describe Swift is to compare it with Objective-C, which was the reference programming language for building Cocoa apps. Objective-C is an object-oriented programming language with similarities to dynamic languages, such as Ruby or Python. It is built on top of C, to which Apple has added features to make it modern, such as blocks, properties, and an Automatic Reference Counter (ARC) to manage the memory.
Swift is an object-oriented programming language with some functional programming characteristics. It aims to flatten the learning curve for the beginner, and to also provide more advanced features for the expert, adding more checks at runtime that could help make apps safer.
Objective-C is a loosely static-typed language; every variable must have a type, but it's possible to define a variable using the id type, reaching a sort of dynamic typing, where the type is evaluated at runtime. Thanks to its powerful runtime environment, it's possible to change the structure of a class-for example, add a method or variable-at runtime. This makes Objective-C a really flexible language, but it is also difficult to manage and prone to creating subtle bugs that are difficult to catch at runtime.
Swift is a strong static-typed language. This means that the type of a variable must be set and is evaluated at compile time. It also lacks any kind of metaprogramming at runtime, but this sternness, added to the functional patterns it supports, should help programmers eliminate an entire class of bugs, allowing apps to be more robust in a faster way.
However, the best way to learn a language is to play with it, and Xcode 6 has brought forth a really nice way to do it.
Let's go to the playground
Usually, the only way to experiment and learn a language until Xcode 5 was by creating a new app and writing code inside any method of that app. Then, you would compile and run it, reading the log or stopping using the debugger.
Xcode introduced the concept of a playground, which isn't an app or a program to be built, but a source file that is constantly compiled and evaluated every time it changes.
Xcode 6 can be downloaded for free from the Mac App Store at www.appstore.com/mac/Xcode. Once it is installed, go to File | New | Playground, as shown in this screenshot:
Without changing anything, you have created your first Swift program! The following screenshot shows our first program:
The playground is split into two: to the left is our code, and to the right is the evaluation of the code on the left-hand side.
If we change the string from "Hello, playground" to "Hello World!", as you can see in the following screenshot, the code is compiled and run without the need to select anything from the menu. This is because the compilation is triggered by the saving operation.
If we make an error, for example, by removing the closing quote from the string, the left part presents a red dot. This dot shows the error type when we click on it. Notice that the right part still presents the result of the previous run. This screenshot displays how the playground shows an error:
With the println() function, it is possible to print messages on a debug console, which can be opened by going to View | Assistant Editor | Show Assistant Editor, as shown in the following screenshot:
The console is basically another view inside the evaluation window, as you can see in this screenshot:
There is much more to learn about playground, but even with this much knowledge, we can dive into Swift without further ado.
The building blocks - variables and constants
As already said, Swift is a strong typed language, which means that every variable must be declared with the type it holds:
let name: String = "Paul" let age: Int = 27Using the let keyword, we define a constant-a variable that cannot change its value-and, as in math, the constant becomes the identity of the value itself. The following screenshot shows what the console looks like when we try to change the constant after we have defined it:
To define a variable, we can use the var keyword:
We can change the value of a variable, paying attention to set a new value of the same kind. Otherwise, an error will be raised, as shown in this screenshot:
Speaking of type declaration, Swift is smarter than just requiring the type of a variable. If the value of the variable is set during its declaration, Swift can understand the type without the need for an explicit type. This feature is called type inference, and it allows us to create more concise code. For example, we can write code like the following:
let bassPlayer = "Paul" let bassPlayerAge = 27 let guitarPlayer = "John" let guitarPlayerAge = 29Obviously, the type is mandatory if a variable is declared without being initialized:
var bassPlayer: String var bassPlayerAge: Int var guitarPlayer: String var guitarPlayerAge: IntBecause it's really difficult to track all the changes made to a mutable variable, it is good practice to use constants as much as we can, and use variables only to contain the status in a small and well-defined scope in which it's easy to understand whether the code is correct or not.
Collect variables in containers
A variable is the minimum information that we can handle, but, sometimes, it is useful to group variables together. Swift provides three types of containers for this purpose: tuple, array, and dictionary.
A tuple is a limited set of heterogeneous values, like this, for example:
let bassPlayer = (name: "Paul", surname: "McCartney", age: 27)In the declaration of a tuple, each piece of information is separated by a comma (,), each variable is a name-value pair separated by a colon (:), and all the elements are surrounded by a pair of parentheses.
To access the elements of a tuple, it is possible to use a dot notation, specifying the name of a variable:
bassPlayer.name // Paul bassPlayer.surname // McCartney bassPlayer.age // 27A tuple can also be defined as an unnamed collection, that is, without specifying the names of the elements:
let bassPlayer = ("Paul", "McCartney", 27)In this case, to access the elements, we must use their positions inside the tuple:
bassPlayer.0 // Paul bassPlayer.1 // McCartney bassPlayer.2 // 27It is also possible to unwrap the values of a tuple and use them in simple external values, assigning each value inside the tuple to specific variables:
let bassPlayer = ("Paul", "McCartney", 27) let (name, surname, age) = bassPlayer println(name) println(surname) println(age)An array is an unnamed list of homogeneous values:
var band = ["Paul", "John"]An array has a number of elements. These elements can be asked for using the count property:
Each element can be accessed using square brackets ([]) around the index of the...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.
File format: PDF
Copy-Protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (only limited: Kindle).
The file format PDF always displays a book page identically on any hardware. This makes PDF suitable for complex layouts such as those used in textbooks and reference books (images, tables, columns, footnotes). Unfortunately, on the small screens of e-readers or smartphones, PDFs are rather annoying, requiring too much scrolling.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our eBook Help page.