Preface - Understanding Swift Programming: Swift 2 (2015)

Understanding Swift Programming: Swift 2 (2015)

Preface

Apple's announcement in June, 2014 that they had developed Swift, a completely new language for iOS and Mac app development, shocked the programming world. It also made Objective-C a dying language, although one dying very slowly.

There was a clear need for a new language. Objective-C was designed in the early 1980s, and while it has been updated (e.g., Objective-C 2.0), those updates have been limited. Building a new object-oriented language by adding object-oriented capabilities based on Smalltalk to the existing C language made sense at the time, but the language has become increasingly anachronistic as newer languages emerged that have exciting capabilities and that do not have the safety issues and general clunkiness that Objective-C has.

For more about Objective-C and how Swift is different from it, read the paper in Appendix A, "What's Different About Swift?" This paper describes what the limitations of Objective-C have been, the philosophy of the new language, and the four goals the designers of Swift have set for the language: Safety, clarity, modernity, and performance.

As I discuss in that paper, Apple has very significantly achieved the first three of these goals, and is very likely to achieve the fourth goal of performance soon. Building a new programming language, including the compiler and other tools, and making the application programming interfaces (Cocoa Touch, etc.) work for it is a huge effort, and Apple is still struggling to complete these tasks. However, it appears that with version 2 of Swift, the language and its tools are very close to what is needed for production use, even for large projects, and when it is launched publicly in the fall I expect that adoption of the language will begin to accelerate. (Swift, as of August, 2015, is #17 on the Tiobe programming popularity index and rising rapidly, while Objective-C is #6, down from its earlier presumed peak of #3, and falling rapidly.)

Audience for the Book

This book is intended for programmers who want to learn how to use Swift to build iOS or Mac apps. Readers should have some prior programming experience with a language like C or one of the scripting languages. Experience with object-oriented programming is obviously helpful, but not required.

The main audience for the book is intended to be those new to Swift, but intermediate and advanced programmers will also benefit from some of the later chapters in the book.

Organization of the Book

This book is intended as both an introduction to the language and a description of some of its more complicated aspects. In all cases I have tried to explain things in simple terms.

Most books on Swift, when they deal with a topic, tell you all about that topic. I don’t do that. Instead, the book is layered. You’ll often get a chapter introducing a topic. Later in the book, you’ll see another chapter, “Topic X Revisited” with less-used, or more detailed, or more complicated aspects of that topic. The purpose is to limit how much you have to absorb at first on a given topic, and also to allow you to more quickly understand how the pieces fit together.

The book includes cartoons, which are intended to lighten the mood. Each cartoon highlights some interesting aspect of Swift in a fun way and helps you visualize it.

The book is divided into four parts, plus appendices.

Part 1 describes the fundamental aspects of the language. Most of this is quite straightforward and involves just minor changes to syntax that exists in most languages. Some exceptions to this are Swift’s strong emphasis on type safety, and optional values, both very important to understand.

Part 2 describes most of the object-oriented aspects of the language. There are a few confusing things, such as Apple's creating structures and enumerations that often work very much like classes. The many different ways of calling functions and methods can seem rather convoluted, and there is seemingly endless flexibility in the syntax for closure expressions that seems confusing at first but ultimately makes it very easy to write compact closure expressions. Understanding the relationships between closures, functions, methods, and closure expressions is important.

Part 3 describes a number of additional topics, ranging from functions as first class citizens to closures to memory management and error handling. It's at this point that you might want to just start writing apps, maybe skimming the rest of the book until you really need it. You need a good conceptual understanding of the Swift language as a whole, but you don't need to know all the details at first—you can look it up when you need it.

Part 4 describes additional object-oriented aspects of the language, including generic programming, initializers, type casting, protocols, extensions, protocol oriented programming, and programming with a mixture of Swift and Objective-C.

Appendix A, as mentioned earlier, analyzes what is different about Swift, particularly with respect to Objective-C.

Appendix B describes Playgrounds, which allows you to easily test out code.

Appendix C describes the interactive REPL system, a command line alternative to Playgrounds.

Appendix D describes how to find additional information about Swift and, particularly, iOS and the Xcode tools, so that you can begin writing apps.

Errors in the Book

It can be enormously frustrating to be learning a new programming language and to discover that some of the examples in the book you are using don’t work. Unfortunately, it’s hard to keep errors out of books, particularly when the language and tools are changing and when it is difficult to paste code into Xcode and Playground to test it. (If you try this, watch out!)

If you find example code that does not work, first check that any imports that are necessary (Foundation, UIKit) have been made. If so, check the book’s web site, understandingswiftprogramming.com.

Please email me with any errors in the book, code or otherwise: understandingswiftprogramming@gmail.com.

How to Develop Your Knowledge and Skill in Swift

Programming is a complex skill. And Swift, despite its aspects that often make it simple and clear, is ultimately a rather complex language. To be proficient, you need to develop several different kinds of knowledge and skill. You need to develop an understanding of the language—what it does and how the different pieces fit together. You also need to develop the skill of quickly understanding the Swift code you read, even thinking in that code. And finally, you need to get the Swift syntax "in your fingers"—so that when you need to write code it just comes out without much in the way of conscious thought.

Reading a book is a very efficient way to acquire information. It is often far more efficient than pounding away at code that you can't get to work because you are missing some tiny but ultimately critical thing in your understanding. Unfortunately, people tend to have limits on how easily they can absorb information from a book, particularly in one sitting. That's where the online exercises can help.

People learn differently, but I think it can be a mistake to get too quickly into writing code when you need to be absorbing new concepts. This is particularly the case for concepts that are new to you. You may want to first read a chapter, away from your computer, in a quiet area, so you are doing only one thing—absorbing the concepts. You then might want to do the online exercises for that chapter.

I suggest then using either the Playground or the REPL interactive tool to try out the code that you see discussed in the chapter. You should experiment around. Change the values from one type to another. Think of short snippets of code that you can write. Get some experience with direct feedback from the compiler.

The order in which you want to do this may depend on your own preferences as well as your background and how new the information is to you.

What You Need to Know to Develop Apps

This book will provide you with the vast majority of what you need to know about Swift. (Swift is still changing, though, and Appendix D will tell you how to tap into additional information about Swift and how it is changing.)

Knowledge and skill in Swift, however, is a relatively small part of what you will need to learn to build apps. You will in particular need to learn the various iOS (or Mac) APIs You will also need to learn how to use the Xcode interactive development environment and its interactive tool for creating user interfaces, Interface Builder. Of course, how much of the APIs you will need to learn depends upon how sophisticated your apps are and what APIs they will need to use.

What's New in Swift 2?

The following is new in Swift 2:

Error handling. A try-catch mechanism for error handling has been added. Error types are defined with an enumeration. A function is defined that uses the throws keyword, indicating that statements in it can throw errors. These statements typically throw an error when appropriate using thethrow keyword and a member value of the enumeration that defines errors. The function is called within a do-try-catch sequence, with the try statement indicating where the potential error is, and catch statements catching the errors. See Chapter 21 on “Error Handling”.

Check API availability. The compiler will produce a warning if a developer tries to use an API that does not exist in the target platform. A statement allows runtime checking of whether a particular operating system version is available before the code involving it is run,with the option of using different code if that version of the API is not available.

Syntax for print statements. The println statement has been replaced by the print(_:) statement, which does the same thing. A variation, print(_:appendNewline:), has a Boolean in the second parameter that indicates whether a newline character should be appended after the string that is printed.

Guard statement. The guard, or guard-else statement, is an alternative to the if-else statement that has the same goal but has a syntax that is often less clumsy and more readable.

Repeat-while statement. This is a replacement for the do-while statement that works the same way but avoids confusion with the do keyword used in error handling.

Protocol extensions and protocol oriented programming. Protocol extensions allow the definition of method implementations (not just specifying methods) that can be obtained by structures, classes, and enumeration in much the same way that methods are inherited from superclasses. This leads to protocol oriented programming, a new approach that is claimed to be often better than using classes. See Chapter 34 on “Protocol Oriented Programming.”

Function pointers. In Swift 2 it is possible to use function pointers in C, which allows for callbacks in some APIs.

Statement labels. A limited form of a “goto” statement is implemented to allow break and continue statements to work better in nested situations.

If-case statement. The matching capabilities previously available only in switch statements are now available with a new if-case statement.

For-in filtering. When using a for-in statement to iterate through a collection such as an array, you can now use a where clause to select items.

What's New in Swift 1.2?

Swift 1.2 is considered by many developers to be a major advance over previous versions.

Much of Swift 1.2 over the previous version 1.1 involves optimizing the compiler to make it run faster, and fixing various bugs in Swift and the code that bridges it to the Cocoa Touch and Foundation APIs.

A few changes to the language itself have been made, as follows:

Sets. Sets, a minor but missing part of the three collections types of arrays, dictionaries and sets, has been added. A set is an unordered group of values that only has one copy of each value—that is, no duplicates. (See Chapter 6, "Sets".)

Optional chaining. Changes have been made to the if-let and if-var syntax for optional bindings that make it easier to handle multiple nested if statements for optional chaining. (See Chapter 26, "Optional Values Revisited".)

Changes to constants. Changes to constants during initialization are no longer allowed.

Zip. A new function, zip, has been added that "zips together" two separate but related arrays into a single array of tuples.

Typecasting operators. The typecasting operators are now as, as! and as?, with the former intended to remind the programmer that downcasting can fail, and the last returning a nil if a downcast has failed.

Markdown in playground comments. A simple way of adding sophisticated displays of comments, known variously as “markup” or “markdown”, has been added. See Appendix B on the Playground.