
Beginning Swift Programming
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
More details
Other editions
Additional editions

Person
Content
INTRODUCTION xxiii
CHAPTER 1: INTRODUCTION TO SWIFT 1
What Is Swift? 2
Why Swift Is Important 3
Setting Up the Environment 3
Creating a Playground Project 4
Creating an iOS Project 6
Swift Syntax 10
Constants 10
Variables 12
String Interpolation: Including Values in Strings 14
Statements 14
Printing 15
Comments 15
Summary 17
CHAPTER 2: DATA TYPES 19
Basic Data Types 20
Integers 20
Types of Integers 21
Integer Operations 22
Integer Literals 22
Floating?]Point Numbers 23
Floating?]Point Operations 23
Floating?]Point Literals 24
Type Alias 25
Boolean 25
Tuples 26
Optional Types 27
Implicitly Unwrapped Optionals 28
Optional Binding 29
Unwrapping Optionals Using "?" 30
Enumerations 30
Using Enumeration in Switch Statements 31
Enumeration Raw Values 32
Auto?]Increment for Raw Values 33
Associated Values 34
Enumeration Functions 35
Summary 36
CHAPTER 3: STRINGS AND CHARACTERS 39
Strings 40
Mutability of Strings 40
Strings as Value Types 40
Characters 41
Concatenating Strings 43
Special Characters 44
Unicode 45
Common String Functions 46
Equality 46
Prefi x and Suffi x 47
Length 47
Substrings 48
Converting Strings to Arrays 51
Type Conversion 51
Interoperability with NSString 52
Casting String to NSString 53
Using NSString Directly 54
String or NSString? 55
Summary 56
CHAPTER 4: BASIC OPERATORS 59
Assignment Operator 60
Arithmetic Operators 61
Addition Operator 61
Subtraction Operator 62
Multiplication Operator 62
Division Operator 63
Modulus Operator 63
Increment and Decrement Operator 63
Compound Assignment Operators 65
Nil Coalescing Operator 65
Comparison Operators 66
Equal To and Not Equal To 66
Greater Than or Equal To 67
Less Than or Equal To 67
Range Operators 68
Logical Operators 69
NOT 69
AND 70
OR 71
Combining Logical Operators 71
Ternary Conditional Operator 72
Summary 73
CHAPTER 5: FUNCTIONS 75
Defi ning and Calling a Function 76
Input Parameters 76
Returning a Value 76
Returning Multiple Values 77
Function Parameter Names 77
External Parameter Names Shorthand 79
Default Parameter Values 79
Variadic (Variable) Parameters 80
Constant and Variable Parameters 81
In?]Out Parameters 82
Function Types 83
Defining a Function Type Variable 83
Calling a Function Type Variable 84
Returning Function Type in a Function 85
Nested Functions 85
Summary 86
CHAPTER 6: COLLECTIONS 89
Arrays 90
Mutability of Arrays 90
Array Data Types 90
Retrieving Elements from an Array 91
Inserting Elements into an Array 91
Modifying Elements in an Array 92
Appending Elements to an Array 92
Checking the Size of an Array 93
Removing Elements from an Array 93
Iterating over an Array 93
Creating an Empty Array 94
Testing Arrays for Equality 95
Dictionaries 96
Mutability of Dictionaries 97
Retrieving Elements from a Dictionary 97
Checking the Size of a Dictionary 98
Modifying an Item in the Dictionary 98
Removing an Item from the Dictionary 99
Iterating over a Dictionary 99
Creating an Empty Dictionary 101
Testing Dictionaries for Equality 101
Copying the Behavior of Arrays and Dictionaries 102
Summary 103
CHAPTER 7: CONTROL FLOW AND LOOPING 107
Flow Control 108
If Statement 108
If?]Else Statement 109
Switch Statement 110
Matching Numbers 111
Matching Characters 112
Fallthrough 112
Matching a Range of Numbers 113
Matching Tuples 114
Value Bindings 115
Where Clause 117
Looping 118
For?]In Loop 118
Traditional For Loop 121
While Loop 122
Do?]While Loop 123
Control Transfer Statements 124
Break Statement 124
Continue Statement 126
Labeled Statement 126
Summary 128
CHAPTER 8: STRUCTURES AND CLASSES 131
Structures 132
Memberwise Initializers 132
Structures as Value Types 133
Comparing Structures 135
Classes 135
Defining a Class 136
Properties 136
Stored Properties 136
Lazy Stored Properties 137
Computed Properties 138
Motivation Behind Computed Properties 139
The newValue keyword 140
Read?]Only Computed Properties 141
Property Observers 141
Typed Properties 143
Initializers 144
Initializers and External Parameter Names 145
Initializing Variables and Constants During Initialization 147
Classes as Reference Types 147
Comparing Instances-Identity Operators 149
Comparing Instances-Equivalence Operators 150
Methods in Classes 151
Instance Methods 151
Local and External Parameter Names for Methods 152
The self Property 154
Type Methods 155
Methods in Structures 155
Summary 157
CHAPTER 9: INHERITANCE 161
Understanding Inheritance 162
Defi ning a Base Class 162
Instantiating a Base Class 162
Creating an Abstract Class 163
Inheriting from a Base Class 164
Overriding Initializers 164
Overloading Initializers 165
Creating Abstract Methods 167
Overloading Methods 169
Preventing Subclassing 170
Types of Initializers 171
Default Initializer 171
Designated Initializers 172
Convenience Initializers and Initializer Chaining 174
Calling Initializers in Subclasses 176
Extensions 177
Extending Methods 177
Extending Properties 177
Access Controls 178
Internal 179
Private 180
Public 181
Summary 181
CHAPTER 10: CLOSURES 185
Understanding Closures 186
Functions as Closures 186
Assigning Closures to Variables 187
Writing Closures Inline 188
Type Inference 188
Shorthand Argument Names 189
Operator Function 190
Trailing Closures 190
Using the Array's Three Closure Functions 190
The map Function 191
Example 1 191
Example 2 192
The filter Function 192
Example 1 192
Example 2 193
The reduce Function 194
Example 1 194
Example 2 195
Using Closures in Your Functions 196
Summary 198
CHAPTER 11: PROTOCOLS AND DELEGATES 201
Understanding Protocols 202
Defining and Using a Protocol 202
Conforming to a Protocol 202
Optional Methods 204
Conforming to Multiple Protocols 206
Property Requirements 206
Initializer Requirements 207
Understanding Delegates 207
Delegates as Event Handlers 208
A Practical Example of Protocols and Delegates 211
Summary 213
CHAPTER 12: GENERICS 217
Understanding Generics 218
Using Generic Functions 218
Multiple Type Parameters 219
Specifying Type Constraint 220
Generic Types 221
Generic Classes 221
Generic Structures 223
Generic Type Extension 224
Using Generics in Protocols 225
Specifying Requirements for Associated Types 228
Summary 229
APPENDIX: EXERCISE ANSWERS 233
INDEX 247
INTRODUCTION
The IT world is an extremely fast-changing one. Small changes occur nearly daily, and every now and then something big happens that changes the entire industry, if not the world. For example, the iPhone, introduced in 2007, transformed the mobile industry overnight, spearheading the new era of the smartphones. The launch of the iPad three years later (2010) changed the way we use our computers, causing many to predict that we are all entering the end of the PC era.
For a long time after its inception in the 1980s, Objective-C was used by NeXT for its NeXTStEP operating system. Mac OS X and iOS both derived from NeXTSTEP, and Objective-C was thus the natural choice of language to use for Mac OS and iOS development. Developers starting on iOS development often complain that Objective-C does not look like a modern programming language (such as Java or C#), and that it is difficult to write and requires spending significant amounts of time trying to learn. For seven years, Apple has improved on the language and the iOS framework, making life easier for developers by introducing helpful features, such as Automatic Reference Counting (ARC), which takes the drudgery out of memory management, and Storyboard, which simplifies the flow of your application user interface. However, this did not stop all the complaints. Furthermore, Apple needed a new language that could take iOS and Mac OS development to the next level.
In 2014, at the Apple World Wide Developers Conference (WWDC), Apple took many developers by surprise by introducing a new programming language: Swift. After seven years, Apple finally released a new language that can replace Objective-C! As you will see throughout this book, Swift is a modern programming language with an easy-to-read syntax, and strict enforcement of type safety.
This book was written with busy developers in mind. It aims to cut through all the technical jargon and dive straight into the language. Of course, the best way to learn any new language is to see code examples, and this book is loaded with them. To get the most from the material, therefore, I strongly recommend that you work through the examples in each chapter as you read them.
WHO THIS BOOK IS FOR
This book is targeted at both beginning iOS developers and experienced Objective-C developers. It assumes a foundation in programming, and an understanding of object-oriented programming (OOP) concepts is required to get the most out of this book.
All the code samples in the chapters were written and tested using the final version of Xcode 6. Because the Swift language is still evolving, expect to see minor tweaks by the time this book is on the market.
HOW THIS BOOK IS STRUCTURED
This book covers the key topics of Swift programming using Xcode 6. It is divided into the following 12 chapters:
Chapter 1, "Introduction to Swift," covers the basic syntax of Swift and how to set up the development environment so that you can test your Swift code.
Chapter 2, "Data Types," covers the basic data types supported in Swift and how to perform the common operations involving them. It also covers the new tuple and optional data types introduced in Swift.
Chapter 3, "Strings and Characters," discusses how strings and characters are managed in Swift. In particular, special emphasis is placed on how the string type in Swift is backwardly compatible with the NSString in Objective-C. Also covered are things you need to be aware of when dealing with Unicode characters.
Chapter 4, "Basic Operators," covers all the commonly used operators supported by Swift. In addition, it discusses the new range operators introduced in Swift.
Chapter 5, "Functions," explains how functions are defined in Swift and the use of internal and external parameter names when calling them.
Chapter 6, "Collections," covers the collection types supported in Swift-arrays and dictionaries.
Chapter 7, "Control Flow and Looping," covers how to make decisions in Swift and how to use the looping statements to execute your Swift code repetitively.
Chapter 8, "Structures and Classes," covers the basics of these programming constructs. It also demonstrates how to define properties and methods in your classes and structures.
Chapter 9, "Inheritance," covers how to create subclasses in Swift and how access control rules affect the accessibility of a member. It also explains how to extend a class using the extension feature.
Chapter 10, "Closures," covers everything you need to know about these blocks of functionality and demonstrates how they enable you to write versatile code in Swift.
Chapter 11, "Protocols and Delegates," discusses a very important part of Swift's design pattern. The protocol and delegate model is the basis on which most of the APIs in iOS and Mac OS programming are based.
Chapter 12, "Generics," covers how Swift embraces this familiar programming concept, which enables the developer to write highly adaptable code that promotes sharing and reusing.
The appendix offers the answers to the exercises found at the end of each chapter.
WHAT YOU NEED TO USE THIS BOOK
In order to follow the examples provided in this book, you need a Mac to install Xcode 6. Xcode 6 is available for download, free, from the Mac App Store. No iOS device is needed to test the code in this book. For testing, you can create either a Playground project or an iOS project, which you can then test on the included iPhone Simulator.
CONVENTIONS
To help you get the most from the text and keep track of what's happening, we've used a number of conventions throughout the book.
NOTE Notes indicates notes, tips, hints, tricks, and asides to the current discussion.
WARNING Warnings hold important, not-to-be-forgotten information that is directly relevant to the surrounding text.
As for styles in the text:
- We highlight new terms and important words when we introduce them.
- We show keyboard strokes like this: Command+A.
- We show file names, URLs, and code within the text like so:
persistence.properties.
We present code in two different ways:
We use a monofont type with no highlighting for most code examples. We use bold to emphasize code that is particularly important in the present context or to show changes from a previous code snippet. SOURCE CODE
As you work through the examples in this book, you should type all the code into Xcode and observe the results. Remember, the best way to learn a language is to experience it yourself and make mistakes. For Chapter 11, you can find the source code for the LBS project at www.wrox/com/go/beginningswift. When at the site, simply locate the book's title (use the Search box or one of the title lists) and click the Download Code link on the book's detail page to obtain all the source code for the book.
After you download the code, just decompress it with your favorite compression tool. Alternatively, go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.
NOTE Because many books have similar titles, you may find it easiest to search by ISBN; this book's ISBN is 978-1-119-00931-3.
ERRATA
We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or a faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration and at the same time help us provide even higher-quality information.
To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page, you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list, including links to each book's errata, is also available at www.wrox.com/misc-pages/booklist.shtml.
If you don't spot "your" error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We'll check the information and, if appropriate, post a message to the book's errata page and fix the problem in subsequent editions of the book.
P2P.WROX.COM
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system for you to post messages relating to Wrox books and related technologies and to interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.
At p2p.wrox.com, you will find a number of different forums that will help you not only as you read this book but also as you develop your own applications. To join the forums, just follow these steps:
- Go to p2p.wrox.com and click the Register link.
- Read the terms of use and click...
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.