Swift Pocket Reference 2nd Edition Programming
for iOS and OS X Anthony Gray install download
https://ebookname.com/product/swift-pocket-reference-2nd-edition-
programming-for-ios-and-os-x-anthony-gray/
Get the full ebook with Bonus Features for a Better Reading Experience on ebookname.com
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
iOS and OS X Network Programming Cookbook 1st Edition
Jon Hoffman
https://ebookname.com/product/ios-and-os-x-network-programming-
cookbook-1st-edition-jon-hoffman/
iOS 8 Programming Fundamentals with Swift Swift Xcode
and Cocoa Basics 1st Edition Matt Neuburg
https://ebookname.com/product/ios-8-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-1st-edition-matt-neuburg/
Cocoa programming for Mac OS X for dummies 1st ed
Edition Tejkowski
https://ebookname.com/product/cocoa-programming-for-mac-os-x-for-
dummies-1st-ed-edition-tejkowski/
Extreme Value and Related Models with Applications in
Engineering and Science 1st Edition Enrique Castillo
https://ebookname.com/product/extreme-value-and-related-models-
with-applications-in-engineering-and-science-1st-edition-enrique-
castillo/
Buddhism Meditation and Free Will A Theory of Mental
Freedom 1st Edition Rick Repetti
https://ebookname.com/product/buddhism-meditation-and-free-will-
a-theory-of-mental-freedom-1st-edition-rick-repetti/
Secret Germany Stefan George and His Circle 1st Edition
Robert E. Norton
https://ebookname.com/product/secret-germany-stefan-george-and-
his-circle-1st-edition-robert-e-norton/
Precalculus 9th Edition Ron Larson
https://ebookname.com/product/precalculus-9th-edition-ron-larson/
The Reflective Journal 1st Edition Barbara Bassot
https://ebookname.com/product/the-reflective-journal-1st-edition-
barbara-bassot/
Beyond Basic Statistics Tips Tricks and Techniques
Every Data Analyst Should Know 1st Edition Kristin H.
Jarman
https://ebookname.com/product/beyond-basic-statistics-tips-
tricks-and-techniques-every-data-analyst-should-know-1st-edition-
kristin-h-jarman/
The New Leadership Challenge 2nd Edition Sheila
Grossman
https://ebookname.com/product/the-new-leadership-challenge-2nd-
edition-sheila-grossman/
2n
d
Co
Ed
ve
rs
iti
Sw
on
if t
2.
1
Swift
Pocket
Reference
PROGRAMMING FOR iOS AND OS X
Anthony Gray
www.it-ebooks.info
www.it-ebooks.info
SECOND EDITION
Swift Pocket Reference
Anthony Gray
www.it-ebooks.info
Swift Pocket Reference
by Anthony Gray
Copyright © 2016 Anthony Gray. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promo‐
tional use. Online editions are also available for most titles (http://safaribook‐
sonline.com). For more information, contact our corporate/institutional sales
department: 800-998-9938 or [email protected].
Editor: Rachel Roumeliotis
Production Editor: Colleen Lobner
Proofreader: Christina Edwards
Indexer: WordCo Indexing Services, Inc.
Interior Designer: David Futato
Cover Designer: Randy Comer
Illustrator: Rebecca Demarest
December 2014: First Edition
November 2015: Second Edition
Revision History for the Second Edition
2015-11-11: First Release
See http://oreilly.com/catalog/errata.csp?isbn=9781491940075 for release
details.
While the publisher and the author have used good faith efforts to ensure that
the information and instructions contained in this work are accurate, the
publisher and the author disclaim all responsibility for errors or omissions,
including without limitation responsibility for damages resulting from the use
of or reliance on this work. Use of the information and instructions contained
in this work is at your own risk. If any code samples or other technology this
work contains or describes is subject to open source licenses or the intellec‐
tual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.
978-1-491-94007-5
[M]
www.it-ebooks.info
Table of Contents
Introduction 1
Conventions Used in This Book 2
Using Code Examples 2
Safari® Books Online 3
How to Contact Us 4
Acknowledgments 5
Getting Started with Swift 2 5
A Taste of Swift 12
Basic Language Features 14
Types 18
Variables and Constants 23
Tuples 27
Operators 30
Strings and Characters 39
Arrays 48
Dictionaries 57
Sets 62
Functions 68
Closures 75
Optionals 81
iii
www.it-ebooks.info
Program Flow 88
Classes 106
Structures 139
Enumerations 144
Access Control 151
Extensions 155
Checking and Casting Types 158
Protocols 162
Memory Management 187
Generics 193
Operator Overloading 201
Ranges, Intervals, and Strides 206
Global Functions 210
Changes From Swift 1.0 215
Index 217
iv | Table of Contents
www.it-ebooks.info
Swift Pocket Reference
Introduction
Swift is an exciting new language from Apple, first announced
at the Apple Worldwide Developers Conference (WWDC)
in June 2014. The language started life as the brainchild
of Chris Lattner, director of Apple’s Developer Tools depart‐
ment, and is the next step in the evolution of Apple’s software
development ecosystem.
Swift brings with it many modern language features, including
type safety, generics, type inference, closures, tuples, protocols,
automatic memory management, and support for Unicode (for
character and string values as well as for identifiers). You can
use a mixture of Swift and Objective-C in a single project, and
either language can call APIs implemented in the other.
The challenge for anyone learning or writing about Swift is that
the language is still evolving. When they introduced it, Apple
stated that the language specification was not final, and that the
syntax and feature set would change. Since the initial release,
there have been two significant updates (versions 1.2 and 2.0),
both of which introduced new features, and in some cases
changed existing features. Fortunately, Xcode can detect most
of the cases where your code is using an older syntax or feature,
and offers hints at what to change to address this.
1
www.it-ebooks.info
Despite the uncertainty of a changing language, Swift continues
to show great promise. It follows on from the company’s other
major developer tools initiatives (all led by Lattner) including
LLVM, Clang, LLDB, ARC, and a series of extensions to
Objective-C, and it’s clear that Apple sees it as the future lan‐
guage of choice for iOS and OS X software development.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames,
and file extensions.
Constant width
Used for program listings, as well as within paragraphs to
refer to program elements such as variable or function
names, databases, data types, environment variables, state‐
ments, and keywords.
Constant width bold
Shows commands or other text that should be typed liter‐
ally by the user.
Constant width italic
Shows text that should be replaced with user-supplied val‐
ues or by values determined by context.
NOTE
This element signifies a general note.
Using Code Examples
You can download code samples that accompany this book at
https://github.com/adgray/SwiftPocketReference2ndEd.
2 | Swift Pocket Reference
www.it-ebooks.info
This book is here to help you get your job done. In general, if
example code is offered with this book, you may use it in your
programs and documentation. You do not need to contact us
for permission unless you’re reproducing a significant portion
of the code. For example, writing a program that uses several
chunks of code from this book does not require permission.
Selling or distributing a CD-ROM of examples from O’Reilly
books does require permission. Answering a question by citing
this book and quoting example code does not require permis‐
sion. Incorporating a significant amount of example code from
this book into your product’s documentation does require per‐
mission.
We appreciate, but do not require, attribution. An attribution
usually includes the title, author, publisher, and ISBN. For
example: “Swift Pocket Reference by Anthony Gray (O’Reilly).
Copyright 2016 Anthony Gray, 978-1-491-94007-5.”
If you feel your use of code examples falls outside fair use or
the permission given above, feel free to contact us at permis‐
[email protected].
Safari® Books Online
Safari Books Online is an on-demand
digital library that delivers expert
content in both book and video form
from the world’s leading authors in technology and busi‐
ness.
Technology professionals, software developers, web designers,
and business and creative professionals use Safari Books
Online as their primary resource for research, problem solving,
learning, and certification training.
Safari Books Online offers a range of plans and pricing for
enterprise, government, education, and individuals.
Safari® Books Online | 3
www.it-ebooks.info
Members have access to thousands of books, training videos,
and prepublication manuscripts in one fully searchable data‐
base from publishers like O’Reilly Media, Prentice Hall Profes‐
sional, Addison-Wesley Professional, Microsoft Press, Sams,
Que, Peachpit Press, Focal Press, Cisco Press, John Wiley &
Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt,
Adobe Press, FT Press, Apress, Manning, New Riders,
McGraw-Hill, Jones & Bartlett, Course Technology, and
hundreds more. For more information about Safari Books
Online, please visit us online.
How to Contact Us
Please address comments and questions concerning this book
to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, exam‐
ples, and any additional information. You can access this page
at http://bit.ly/swift_pocket_ref_2e.
To comment or ask technical questions about this book, send
email to [email protected].
For more information about our books, courses, conferences,
and news, see our website at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
4 | Swift Pocket Reference
www.it-ebooks.info
Acknowledgments
I would like to thank fellow O’Reilly author Paris Buttfield-
Addison for urging me (repeatedly) to write this book. He and
his partner-in-crime, Jon Manning, suffer from boundless opti‐
mism and seem to regard “no” as a challenge rather than as a
defeat. I’d also like to thank Rachel Roumeliotis and the other
fine folk at O’Reilly for having faith in me and for shepherding
the project (and the update) through to completion. Special
thanks also go to the readers of the early release editions, who
took the time to provide feedback and suggestions for improve‐
ment, for which I’m deeply grateful.
Getting Started with Swift 2
To code in Swift 2, you should be using Xcode 7 or later (avail‐
able for free on the Mac App Store), which runs on either OS X
10.10 (Yosemite) or OS X 10.11 (El Capitan). You might also
consider signing up as a registered Apple developer (with free
and paid tiers) to gain access to a wealth of documentation and
other developer resources at https://developer.apple.com.
You can use the version of Swift built into Xcode 7 to compile
programs that will run on OS X 10.9 or higher, and on iOS 7
or higher.
After you have downloaded and installed Xcode 7, go ahead
and run it and allow it to install the various tools it comes bun‐
dled with. When installation is complete, there are a number of
ways you can get started with Swift:
• Click File → New Project to create a new Xcode project.
The project wizard opens and offers you the choice
of using Swift or Objective-C as the language for the
project.
• Click File → New Playground to create a new playground
document. Playgrounds are single-window dynamic
environments in which you can experiment with Swift
Acknowledgments | 5
www.it-ebooks.info
language features and see results instantly alongside the
code you enter.
• Create a Swift script and run it from the command line in
the OS X terminal.
• Use the Swift Read-Evaluate-Print-Loop (REPL) in the
OS X terminal.
Let’s look at the REPL, Swift scripting, and playgrounds in
more detail.
NOTE
As of this writing, some features of Swift and Xcode 7 are
still unstable, but the situation improves with each release.
Occasionally, you might need to quit and restart Xcode to
get it back to a sensible state.
The Swift REPL
The Swift REPL provides command-line access to Swift and
behaves like an interpreter. You can declare variables and con‐
stants, define functions, evaluate expressions, and use most
other language features; they will be compiled and executed
immediately.
Multiple Xcode installations
If you have more than one installation of Xcode on your com‐
puter, you will need to use the xcode-select command to
choose the Xcode 7 environment as the active developer direc‐
tory. In the terminal, type the following command:
sudo xcode-select -s /Applications/Xcode.app
When prompted, provide your administrator username and
password. If you have installed Xcode in a different location or
6 | Swift Pocket Reference
www.it-ebooks.info
changed its name, replace the path in the command with the
location and name of your installed release.
Starting the REPL
To start the REPL so you can test Swift language features, use
the following command:
xcrun swift
If you’ve never used Xcode before, you might see an authenti‐
cation prompt from a process called Developer Tools Access (see
Figure 1), prompting you for a username and password. You
will need to enter an administrator username and password to
continue. After you enter these, you might see the following
error message:
error: failed to launch REPL process: process
exited with status -1 (lost connection)
At this point, type the xcrun swift command again. This time,
the REPL should start normally.
Figure 1. The Developer Tools Access prompt
When the REPL starts, you will see the following output:
Welcome to Swift! Type :help for assistance.
1>
Getting Started with Swift 2 | 7
www.it-ebooks.info
You’re now ready to try your first code in Swift. Try the
print function:
1> print ("Hello, World")
Hello, World
2>
The REPL is a great way to test Swift features and experiment
with the language.
Swift as a Scripting Language
You can use Swift as a scripting language, much like Perl,
Python, or Ruby. To use Swift in this manner, ensure the first
line of the script contains the path to the Swift “interpreter.” If
you want to try using Swift this way, type the following into a
text file named hello.swift:
#!/usr/bin/swift
print ("Hello, World")
Next, ensure the script is marked as executable with a chmod
command:
chmod u+x hello.swift
Now, run the script as follows:
./hello.swift
Swift will compile your program, and assuming there are no
syntax errors, will execute it.
Swift Playgrounds
To explore Swift in a playground, on the Xcode menu bar, click
File → New Playground, or click the “Get started with a play‐
ground” option in the Welcome to Xcode window.
You are then prompted to enter a playground name (which
becomes the saved document’s name) and a platform (iOS or
OS X), as demonstrated in Figure 2.
8 | Swift Pocket Reference
www.it-ebooks.info
Figure 2. Creating a Swift playground
Once you’ve entered your playground name and selected your
platform, click Next. You will then be prompted to select a loca‐
tion to which to save the file. When the file has been saved, you
see the initial playground window, as shown in Figure 3.
Figure 3. The initial playground window
The playground template imports either the Cocoa or UIKit
Framework, depending on whether you selected OS X or iOS
as your playground platform. This means you can experiment
not just with basic Swift language features, but also with many
Getting Started with Swift 2 | 9
www.it-ebooks.info
of the features provided by the framework, such as drawing
views and images, and even implementing basic animations.
The playground also displays a line of code:
var str = "Hello, playground"
To the right of that code is the value “Hello, playground.” This
demonstrates one of the most useful features of the play‐
ground: the result of every expression displays alongside it in
the results sidebar.
Below the existing text, type the following:
for var i=0; i<10; i++ {
print (i)
}
The results sidebar now displays the text “(10 times)” to con‐
firm the number of executions of the loop.
If you hover the pointer over the entries in the results sidebar
(Figure 4), you’ll see two symbols. The eye-like symbol pro‐
vides a Quick Look view of the value (this includes viewers for
complex data such as strings, arrays, dictionaries, images,
views, URLs, and more). The button symbol opens a Result
view in line with the Swift code that generated it (Figure 5).
Figure 4. Accessing Quick Look and the Result view from the
results sidebar
10 | Swift Pocket Reference
www.it-ebooks.info
Figure 5. Showing a Results view in line with Swift code
Note that a Results view generally only shows the last result
that was generated (9, in the case of the for loop). If you right-
click in a Results view you’ll expose a menu that allows you to
choose between the latest value and the value history.
The Debug Area (Figure 6) shows you console output (e.g., text
output by the print function). To show the Debug Area, click
the small upward-pointing triangle inside the square box at the
lower-left of the Playground window.
Figure 6. The Debug area showing console output
You can also open the Debug Area by going to the Xcode menu
bar and clicking View → Debug Area → Show Debug Area, or
you can use the keyboard shortcut Command-Shift-Y.
Getting Started with Swift 2 | 11
www.it-ebooks.info
NOTE
For an excellent introduction to playgrounds, see the
recording of session 408 (Swift Playgrounds) from the
2014 Worldwide Developers Conference, and session 405
(Authoring Rich Playgrounds) from the 2015 Worldwide
Developers Conference.
A Taste of Swift
Let’s dive right in. What follows is a simple program written in
Swift. Work through carefully to get a sense of some of the fea‐
tures of the language.
The first thing the program does is define a pair of arrays: one
named users, and another named ages for those users. This is
meant to represent raw input of disassociated data that needs to
be merged and then used as the basis of a report:
// some raw data to process
var users = ["xavier", "ryan", "brenda", "james", "sarah"]
var ages = [32, 28, 24, 41, 19]
The next section of code is a pair of extensions to the String
type. Swift has built-in support for Unicode strings, but it also
has a very flexible extension mechanism with which you can
add new features to the language—even to built-in types. The
extension adds two new member functions to the String type
that can take a string and return a copy that is padded with
leading or trailing spaces to a specified width:
// add some extensions to the String type
extension String
{
func leadingSpaces(width: Int) -> String
{
var s = String(self)
for i in s.characters.count..<width {
s = " " + s
}
return s
}
12 | Swift Pocket Reference
www.it-ebooks.info
func trailingSpaces (width: Int) -> String
{
var s = String(self)
for i in s.characters.count..<width {
s = s + " "
}
return s
}
}
Next, a dictionary merged is declared. This is an associative
array of key/value pairs to store each user’s name and age. The
variable totalAge is also declared, to store the sum of all of the
ages so that later the average age of all users can be calculated:
// a dictionary to store merged input
var merged = [String: Int]()
var totalAge = 0.0
With the dictionary defined, the next step is to iterate over the
two input arrays, merging them into the merged dictionary. The
dictionary utilizes the user’s name as the key and the user’s age
as the value:
// merge the two arrays into a dictionary
for var i=0; i < ages.count; i++ {
merged[users[i]] = ages[i]
}
At this point the dictionary contains all of the raw input, and
it’s time to generate a report. We want to list the users in sorted
order, and print each user’s age along with their name using
trailing and leading spaces so the names are left-aligned under
one another and the ages are right-aligned:
// interate over the dictionary in sorted order
// and generate a report
for user in merged.keys.sort() {
let age = merged[user]!
totalAge += Double(age)
let paddedUser = user.trailingSpaces(10)
let paddedAge = "\(age)".leadingSpaces(3)
print ("\(paddedUser) \(paddedAge)")
}
A Taste of Swift | 13
www.it-ebooks.info
print (merged.count, "users")
print ("average age:", totalAge / Double(merged.count))
The output of the program looks like this:
brenda 24
james 41
ryan 28
sarah 19
xavier 32
5 users
average age: 28.8
If you’ve followed along, you should have a good sense of some
of the language’s capabilities. You’ve already been exposed to
comments, arrays and dictionaries, various loop types, type
conversion, function calls, extensions, string interpolation, and
console output.
The remainder of this book will take you on a tour of these top‐
ics and all of the major aspects of the Swift language. Generally,
the intention is to cover basic features before more advanced
features, but at times it is necessary to dip into advanced topics
early on. When this happens, we’ll try to warn you in advance
and point to where you can find more coverage.
Finally, note that this book is about the Swift language, not
about iOS or OS X development. O’Reilly has some excellent
titles that cover using Swift in those broader contexts, but the
examples and discussion you’ll find here are deliberately limi‐
ted to pure Swift as much as possible.
Basic Language Features
Before delving into the specifics of the language such as data
types or program flow, let’s take a look at some of the more
general aspects of Swift source code.
14 | Swift Pocket Reference
www.it-ebooks.info
Comments
Swift supports C-style comments. Comments that extend to the
end of the current line begin at a double forward-slash, as illus‐
trated here:
// this is a comment
print ("Hello, world") // really?
For multiline comments, you enclose them between a forward-
slash followed by an asterisk at the beginning and end them
with an asterisk followed by a forward-slash, as shown in
the following:
/*you could be excused when looking at this comment
for thinking that it was written in C! */
Unlike C, Swift supports multiline comment nesting. Swift
treats the following as a nested comment block, whereas tradi‐
tional C compilers will report an error at the last */:
/*
/* Original comment here */
*/
Multiline comment nesting makes it possible for you to define
blocks of commented code using the /* and */ comment mark‐
ers without having to first check whether an inner multiline
comment block exists.
Semicolons
Semicolons in Swift are only required when you need to sepa‐
rate multiple statements on a single line. They are not required
at the end of a statement if that is the last statement on the line
(but it is not an error to use them):
var a = 45; // semicolons are optional
var b = 55
Whitespace
Swift uses whitespace to separate tokens, but whitespace has no
other intrinsic meaning. Whitespace include spaces, tabs, line
Basic Language Features | 15
www.it-ebooks.info
feeds, carriage returns, vertical and horizontal tabs, and the
null character.
Because whitespace is ignored, you can use line breaks to split
long lines at token boundaries. Thus, the following two state‐
ments are equivalent:
var a = 45
var a
=
45
There is no formal way to split a long string over multiple lines
as there is in C or Objective-C, but strings can be concatenated
by using the + operator. So, you could split a long string
like this:
let longstr = "Hello there this is a very " +
"long string split over two lines"
Naming Conventions
There are some conventions in relation to naming entities you
are strongly urged to follow. The principal conventions are:
• Names for classes, structures, enumerations, protocols,
and types should begin with an uppercase letter, and use
camel case for the remainder of the name.
• Names for functions, methods, variables, and constants
should begin with a lowercase letter, and use camel case
for the remainder of the name.
Importing Code from Other Modules
In C-like languages, the usual way to use code from other parts
of a project or from libraries or frameworks is by using the
#include directive. When placed in a source file, this directive
instructs the compiler to read a header file into the compilation
process.
16 | Swift Pocket Reference
www.it-ebooks.info
The header file declares what classes, methods, functions, and
external variables are provided by the external code, and are
therefore valid to call or access in the source file that hosts the
#include directive. The feature provided by the code, or links
to it, are linked into the executable file at the last stage of the
compilation process by a program called a linker.
Swift does away with header files and the need to include them.
Instead, Swift uses the import command, which imports the
definitions made available by another module.
The basic syntax is as follows:
import ModuleName
import Cocoa
Used in this way, everything that ModuleName makes public is
imported.
If a module provides submodules, you can import a specific
submodule, with this syntax:
import ModuleName.SubmoduleName
import Foundation.NSDate
If you only want to import a single feature from a module, use
this syntax:
import Feature ModuleName.SymbolName
import func Darwin.sqrt
This last directive imports just the sqrt function from the
Darwin module. Feature describes the type of the entity to be
imported; the type can be one of the following: class, enum,
func, protocol, struct, typealias, or var (all of which are
described throughout the remainder of this book).
You can import most of the standard OS X and iOS frame‐
works into a Swift project, including, for example, AppKit,
Cocoa, CoreData, Darwin, Foundation, UIKit, and WebKit.
Refer to Apple’s documentation on OS X and iOS for
more information on these and other frameworks at https://
developer.apple.com.
Basic Language Features | 17
www.it-ebooks.info
In most applications, you’ll only need to import Cocoa (for OS
X applications) or UIKit (for iOS applications), because they in
turn import most other modules that are normally required for
these application types.
If you are using the Xcode editor, you can see what additional
submodules these modules import or make available by hold‐
ing down Command-Option and simultaneously clicking the
module name in the line that imports that module.
Types
Swift supports the standard data types you would expect in a
modern programming language. These are listed in Table 1.
Table 1. Supported data types in Swift
Data Type Description
Bool Boolean value (true, false)
Int Signed integer value
UInt Unsigned integer value
Double Double-precision (64-bit) floating-point value
Float Single-precision (32-bit) floating-point value
Character A single Unicode character
String An ordered collection of characters
Specific Integer Types
Int and UInt are 32- or 64-bit values, as determined by the
underlying platform. Swift also supports integer types of spe‐
cific size (and hence numeric range). Table 2 shows the range
of values for each type.
18 | Swift Pocket Reference
www.it-ebooks.info
Table 2. Specific integer types and their value ranges
Name Type Range
Int8 Signed 8-bit integer –128 to 127
UInt8 Unsigned 8-bit integer 0 to 255
Int16 Signed 16-bit integer –32,768 to 32,767
UInt16 Unsigned 16-bit integer 0 to 65,535
Int32 Signed 32-bit integer –2,147,483,648 to 2,147,483,647
UInt32 Unsigned 32-bit integer 0 to 4,294,967,295
Int64 Signed 64-bit integer –263 to 263–1
UInt64 Unsigned 64-bit integer 0 to 264–1
You can determine the maximum and minimum values that
can be stored by each integer type by using the max and min
properties, as demonstrated in the following example:
UInt8.max // returns 255
Int16.min // returns -32768
Numeric Literals
Numeric literals can be expressed in decimal, binary, octal, or
hexadecimal, as presented in Table 3.
Table 3. Expressing numeric literals
Prefix Base Example(s)
None Decimal 17, 1024, 2.767, 2.5e2
0b Binary 0b10001011
0o Octal 0o213
0x Hexadecimal 0x8C, 0x4.8p2
When using numeric literals, also note the following:
• Floating-point literals may be followed by an optional
exponent, which is expressed with an e for decimal
Types | 19
www.it-ebooks.info
floating-point literals, or a p for hexadecimal
floating-point literals, which is in turn followed by the
exponent itself, in decimal. For example, e3 represents a
decimal exponent that multiplies the mantissa by 103,
and p4 represents a hexadecimal exponent that multiplies
the mantissa by 24. Examples include 2.7e4, which equa‐
tes to 2.7 x 104, and 0x10.4p2, which equates to 0x10.4 x
22 (the decimal equivalent being 16.25 x 22).
• To be inferred as a floating-point value, a literal without
an exponent must have a decimal point with digits on
either side. The presence of an exponent removes the
requirement for a decimal point if it is not needed (e.g.,
5e2 evaluates to 5.0 x 102).
• Numeric literals can include underscores (but not com‐
mas) to aid readability. 1_000_000 and 1_00_00_00 are the
same as 1000000.
• Floating-point literals are treated as Double values, unless
they are used in a Float context.
Character and String Literals
Character literals are single characters surrounded by double
quotes (unlike C-based languages, in which single quotes are
used), as shown here:
"A"
"B"
"!"
String literals are character sequences surrounded by double
quotes:
"Hello, World"
The compiler cannot distinguish between a character literal
and a single-character string literal. Literals enclosed in double
quotes are treated by the compiler as strings, unless they appear
in a character context, such as in assignment:
20 | Swift Pocket Reference
www.it-ebooks.info
let someChar: Character = "C"
// "C" is treated as a character literal
var c: Character
c = "A"
// "A" is treated as a character literal
Type Aliases
The typealias keyword defines an alternative name for an
existing type. The following example equates the identifier Byte
with the type UInt8:
typealias Byte = UInt8
After this declaration, Byte can then be used as a type anywhere
that UInt8 can be used, such as in the following example:
var acc: Byte = 64
Aliases can be created for any type, including for example,
function types:
typealias DoubleInDoubleOut = (Double) -> Double
This creates a type alias for a function that takes one parameter
of type Double, and returns a result of type Double. This alias
can be used anywhere this function signature would normally
be written, as in the following example:
var f: DoubleInDoubleOut = {
return $0 * $0
}
f(12.0)
// returns 144.0
See also the sections “Tuples” on page 27, “Functions” on page
68, and “Protocols” on page 162 for related examples of type
aliases.
Nested Types
Swift supports the definition of types within types, as shown in
this example:
class A
{
Types | 21
www.it-ebooks.info
class B
{
var i = 0
}
var j = B()
var k = 0
}
Although you can use such nested definitions to provide utility
classes, structures, or enumerations to support the implementa‐
tion of the outer class, the nested type definitions are visible
outside the class as well. For the preceding definition, you can
create instances of A and B as follows:
var a = A()
var b = A.B()
a.j.i = 2
b.i = 5
If a class contains a nested enumeration, as follows:
class C
{
enum TravelClass
{
case First, Business, Economy
}
// rest of class definition
}
then the enumeration can be accessed outside the class by spec‐
ifying the “path” to the enumeration values, as follows:
var t = C.TravelClass.First
Other Types
In addition to the types already discussed, you can use many
other Swift language elements in a type context, or they can
behave as types. These include classes, structures, enumera‐
tions, functions, and protocols. These topics are covered in
later sections of this book.
22 | Swift Pocket Reference
www.it-ebooks.info
Variables and Constants
Variables and constants must be declared before you use them.
You declare variables by using the var keyword, followed by
the variable’s name, a colon, and then its type, as shown here:
var name: Type
var anInt: Int
var aStr: String
var aChar: Character
You can assign values to variables at the same time you declare
them:
var anotherInt: Int = 45
var anotherStr: String = "Frodo"
Swift uses type inferencing, which means you don’t need to
specify a variable’s type if you assign that variable a value when
you declare it:
var someInt = 45
var someDouble = 23.0, someStr = "Strings too"
You declare constants by using the let keyword. They look like
variables because of the way they are created and used, but they
are immutable—meaning they cannot be changed. Because a
constant cannot be changed, it must be assigned a value when
it is declared (the exception is for constant properties in classes
and structures, which can have their value assigned during ini‐
tialization—see “Classes” on page 106 and “Structures” on page
139 for more information):
let name: Type = expr
let constFloat: Float = 23.1
let constStr: String = "Bilbo"
As with variables, the type of a constant will be inferred from
the value you assign to it, so in most circumstances, you do not
need to specify the type:
let someConstFloat = 23.1
let someConstStr = "Bilbo"
Variables and Constants | 23
www.it-ebooks.info
You can declare the type explicitly for circumstances in which
the inferred type is not desired. This is useful when you want to
declare a Character type where String might otherwise be
inferred, or a Float type where a Double might be inferred, as
illustrated here:
let c: Character = "A"
// "A" is otherwise inferred to be a String
let f: Float = 3.14159
// 3.14149 is otherwise inferred to be a Double
The names of variables and constants can contain most Uni‐
code and other characters. They cannot begin with a number.
Some keywords are reserved for specific language features, and
you cannot use them as identifiers for variables and constants.
Examples include class, func, let, var, and so on. However, if
you enclose a keyword with backticks, you can use it as an
identifier, like this:
var func = 4 // not allowed – func is reserved
var `func` = 4 // allowed
Despite this, you should be wary of using backticks as a means
of using keywords as identifiers. A best practice is to avoid
using reserved keywords at all.
Computed Variables
A computed variable is not a variable in the usual sense—it is
not a value that is stored in memory and read whenever it is
referenced in an expression or during assignment. Instead,
computed variables are functions that look like variables.
A computed variable contains two functions: a getter (identified
with the keyword get, which returns the computed value) and
a setter (identified with the keyword set, which might initialize
the conditions that affect the value returned by the getter). The
declaration looks as follows:
var variableName: someType {
get {
// code that computes and returns
// a value of someType
24 | Swift Pocket Reference
www.it-ebooks.info
Exploring the Variety of Random
Documents with Different Content
The text on this page is estimated to be only 26.42%
accurate
364 SYLVIE AND BRUNO CONCLUDED. "It ca'n't have
Introductory Verses at the end, can it ? " said Sylvie. " Wait till you
hear it," said the Professor : " then you'll see. I'm not sure it hasn't
some in the middle, as well." Here he rose to his feet, and there was
an instant silence through the Banqueting-Hall: they evidently
expected a speech. " Ladies, and gentlemen," the Professor began, "
the Other Professor is so kind as to recite a Poem. The title of it is '
The PigTale.' He never recited it before ! " (General cheering among
the guests.) " He will never recite it again ! " (Frantic excitement,
and wild cheering all down the hall, the Professor himself mounting
the table in hot haste, to lead the cheering, and waving his
spectacles in one hand and a spoon in the other.) Then the Other
Professor got up, and began :— Little Birds are dining Warily and
well, Hid in mossy cell: Hid, 1 say, by waiters Gorgeous in their
gaiters — I've a Tale to tell.
The text on this page is estimated to be only 22.73%
accurate
XXIll] THE PIG-TALE 365 Little Birds are feeding Justices
with jam, Rich in frizzled ham : Rich, I say, in oysters Haunting
shady cloisters — That is what I am. Little Birds are teaching
Tigresses to smile, Innocent of guile : Smile, I say, not smirkle —
Month a semicircle, That's the proper style ! Little Birds are sleeping
All among the pins, Where the loser wins: Where, I say, he sneezes
When and how he pleases So the Tale begins. jT-~lH_> ^^ fflk
gMpfrt
The text on this page is estimated to be only 24.89%
accurate
366 SYLVIE AND BRUNO CONCLUDED. There was a Pig
that sat alone Beside a ruined Pump : By day and night he made his
moan — It would have stirred a heart of stone To see him wring his
hoofs and groan, Because he could not jump. A certain Camel heard
him shout A Camel with a hump. " Oh, is it Grief, or is it Gout ? What
is this bellowing about ? " That Pig replied, with quivering snout,
"Because I cannot jump f" That Camel scanned Jiirn, dreamy-eyed. "
Met/links you are too plump. I never knew a Pig so wide — That
wobbled so from side to side — Who could, however much he tried,
Do such a thing as jump ! " Yet mark those trees, two miles away,
All clustered in a clump: If you could trot there twice a day, Nor ever
pause for rest or play, In the far future Who can say ?You may be fit
to jump!'
The text on this page is estimated to be only 25.38%
accurate
xxin] THE PIG-TALE. 367 That Camel passed, and left him
there Beside the ruined Pump. Oh, horrid was that Pig's despair ! His
shrieks of anguish filled the air. He wrung his hoofs, he rent his hair,
Because he could not jump. There was a Frog that wandered by A
sleek and shining lump: Inspected him with fishy eye,
The text on this page is estimated to be only 24.82%
accurate
368 SYLVIE AND BRUNO CONCLUDED. And said " O Pig,
what makes you cry ?" And bitter was that Pig's reply, " Because I
cannot jump ! " That Frog he grinned a grin of glee, And hit his
chest a tJiump. " O Pig" lie said, " be ruled by me, A nd you shall see
what you shall see. This minute, for a trifling fee, Til teach you how
to jump ! " You may be faint from many a fall, And bruised by many
a bump: But, if you persevere through all, And practise first on
something small, Concluding with a ten-foot wall, You'll find that you
can jump ! " That Pig looked up with joyful start : " Oh Frog, you are
a trump ! Your words have healed my inward smartCome, name
your fee and do your part : Bring comfort to a broken heart, By
teaching me to jump ! " " My fee shall be a mutton-chop, My goal
this ruined Pump. Observe with what an airy flop
The text on this page is estimated to be only 23.46%
accurate
XXIIl] THE PIG-TALE. 369 / plant myself upon the top !
Nozv bend your knees and take a hop, For that's the way to jump ! "
Uprose that Pig, and rushed, full whack. Against the ruined Pump :
Rolled over like an empty sack, And settled down upon his back,
While all his bones at once went ' Crack ! ' It was a fatal jump. B B
The text on this page is estimated to be only 26.98%
accurate
370 SYLVIE AND BRUNO CONCLUDED. When the Other
Professor had recited this Verse, he went across to the fire-place,
and put his head up the chimney. In doing this, he lost his balance,
and fell head-first into the empty grate, and got so firmly fixed there
that it was some time before he could be dragged out again. Bruno
had had time to say " I thought he wanted to see how many peoples
was up the chimbley." And Sylvie had said " Chimney not chimbley."
And Bruno had said " Don't talk 'ubbish ! " All this, while the Other
Professor was being extracted. " You must have blacked your face ! "
the Empress said anxiously. " Let me send for some soap ? " "
Thanks, no," said the Other Professor, keeping his face turned away.
" Black's quite a respectable colour. Besides, soap would be no use
without water." Keeping his back well turned away from the
audience, he went on with the Introductory Verses ;
The text on this page is estimated to be only 23.55%
accurate
xxm] THE PIG-TALE. 371 Little Birds are writing Interesting
books, To be read by cooks : Read, I say, not roasted— Letterpress,
when toasted, Loses its good looks. Little Birds are playing Bagpipes
on the shore, Where the tourists snore . ' Thanks ! " they cry. " ' Tis
thrilling ! Take, oh take this shilling! Let us have no more ! " Little
Birds are bathing Crocodiles in cream, Like a happy dream : Like, but
not so lasting — Crocodiles, when fasting, A re not all they seem !
The text on this page is estimated to be only 23.29%
accurate
372 SYLVIE AND BRUNO CONCLUDED. That Camel passed,
as Day grew dim Around the ruined Pump. " O broken heart ! O
broken limb ! ft needs" that Camel said to him, " Something more
fairy-like and slim, To execute a jump ! " That Pig lay still as any
stone, A nd could not stir a stump : Nor ever, if the trutJi were
known,
The text on this page is estimated to be only 24.13%
accurate
xxiii] THE PIG-TALE. Was lie again observed to moan, Nor
ever wring liis hoofs and groan, Because he could not jump. Tliat
Frog made no remark, for he Was dismal as a dump : He knew the
consequence must be That lie would never get his fee — And still he
sits, in miserie, Upon that ruined Pump ! 373 "It's a miserable story!"
said Bruno. "It begins miserably, and it ends miserablier. I think I
shall cry. Sylvie, please lend me your handkerchief."
The text on this page is estimated to be only 25.38%
accurate
374 SYLVIE AND BRUNO CONCLUDED. " I haven't got it
with me," Sylvie whispered. " Then I won't cry," said Bruno manfully.
"There are more Introductory Verses to come," said the Other
Professor, "but I'm hungry." He sat down, cut a large slice of cake,
put it on Bruno's plate, and gazed at his own empty plate in
astonishment. "Where did you get that cake?" Sylvie whispered to
Bruno. " He gived it me," said Bruno. " But you shouldn't ask for
things ! You know you shouldn't ! " " I didrit ask," said Bruno, taking
a fresh mouthful : " he gived it me." Sylvie considered this for a
moment : then she saw her way out of it. " Well, then, ask him to
give me some ! " " You seem to enjoy that cake ? " the Professor
remarked. " Doos that mean ' munch ' ? " Bruno whispered to Sylvie.
Sylvie nodded. " It means 'to munch' and ' to like to munch.' ' Bruno
smiled at the Professor. " I doos enjoy it," he said.
The text on this page is estimated to be only 24.47%
accurate
xxni] THE PIG-TALE. 375 The Other Professor caught the
word. " And I hope you're enjoying yourself, little Man ? "" he
enquired. Bruno's look of horror quite startled him. " No, indeed I
aren't!" he said. The Other Professor looked thoroughly puzzled. "
Well, well ! " he said. " Try some cowslip wine ! " And he filled a
glass and handed it to Bruno. " Drink this, my dear,, and you'll be
quite another man ! " " Who shall I be ? " said Bruno, pausing in the
act of putting it to his lips. " Don't ask so many questions ! " Sylvie
interposed, anxious to save the poor old man from further
bewilderment. " Suppose we get the Professor to tell us a story."
Bruno adopted the idea with enthusiasm. " Please do ! " he cried
eagerly. " Sumfin about tigers and bumble-bees and robinredbreasts,
oo knows ! " " Why should you always have live things in stories ?"
said the Professor. "Why don't you have events, or circumstances ? "
"Q\\t please invent a story like that! "cried Bruno.
The text on this page is estimated to be only 26.29%
accurate
376 SYLVIE AND BRUNO CONCLUDED. The Professor began
fluently enough. " Once a coincidence was taking a walk with a little
accident, and they met an explanation a very old explanation so old
that it was quite doubled up, and looked more like a conundrum " he
broke off suddenly. " Please go on ! " both children exclaimed. The
Professor made a candid confession. " It's a very difficult sort to
invent, I find. Suppose Bruno tells one, first." Bruno was only too
happy to adopt the suggestion. " Once there were a Pig, and a
Accordion, and two Jars of Orange-marmalade — " The dramatis
persons" murmured the Professor. " Well, what then ? " " So, when
the Pig played on the Accordion," Bruno went on, " one of the Jars
of Orangemarmalade didn't like the tune, and the other Jar of
Orange-marmalade did like the tune — I know I shall get confused
among those Jars of Orange-marmalade, Sylvie ! " he whispered
anxiously. " I will now recite the other Introductory Verses," said the
Other Professor.
The text on this page is estimated to be only 24.26%
accurate
XXIll] THE PIG-TALE. 377 Little Birds are choking Baronets
with him, Taught to fire a gun : TaugJit, I say, to splinter Salmon in
the zvinter — Merely for the fun. Little Birds are hiding Crimes in
carpet-bags, Blessed by happy stags: Blessed, I say, though beaten
— Since our friends are eaten When the memory flags. Little Birds
are tasting Gratitude and gold, Pale with sudden cold: Pale, I say,
and wrinkled — When the bells have tinkled, And the Tale is told.
The text on this page is estimated to be only 24.17%
accurate
SYLVIE AND BRUNO CONCLUDED. That Camel passed, as
Day grew dim Around the ruined Pump. " O broken heart ! O broken
limb ! It needs" that Camel said to him, " Something more fairy-like
and slim, To execute a jump ! " That Pig lay still as any stone, A nd
could not stir a stump : Nor ever, if the truth were known,
The text on this page is estimated to be only 25.30%
accurate
XXIII] THE PIG-TALE. 373 Was lie again observed to moan,
Nor ever wring his hoofs and groan, Because he could not jump.
That Frog made no remark, for he Was dismal as a dump : He knew
the consequence must be That he would never get his fee — And
still he sits, in miser ie, Upon that ruined Pump ! "It's a miserable
story!" said Bruno. " It begins miserably, and it ends miserablier. I
think I shall cry. Sylvie, please lend me your handkerchief."
The text on this page is estimated to be only 27.71%
accurate
380 SYLVIE AND BRUNO CONCLUDED. The Lord Chancellor
wrung his hands in despair. " He is mad, good people! " he was
beginning. But both speeches stopped suddenly and, in the dead
silence that followed, a knocking was heard at the outer door. "
What is it ? " was the general cry. People began running in and out.
The excitement increased every moment. The Lord Chancellor,
forgetting all the rules of Court-ceremony, ran full speed down the
hall, and in a minute returned, pale and gasping for breath.
The text on this page is estimated to be only 25.74%
accurate
CHAPTER XXIV. THE BEGGAR'S RETURN. " YOUR Imperial
Highnesses ! " he began. " It's the old Beggar again! Shall we set
the dogs at him ? " " Bring him here ! " said the Emperor The
Chancellor could scarcely believe his ears. " Here, your Imperial
Highness ? Did I rightly understand .' " Bring him here ! " the
Emperor thundered once more, The Chancellor tottered down the
hall and in another minute the crowd divided, and the poor old
Beggar was seen entering the Banqueting- Hall.
The text on this page is estimated to be only 28.52%
accurate
382 SYLVIE AND BRUNO CONCLUDED. He was indeed a
pitiable object : the rags, that hung about him, were all splashed
with mud : his white hair and his long beard were tossed about in
wild disorder. Yet he walked upright, with a stately tread, as if used
to command : and strangest sight of all Sylvie and Bruno came with
him, clinging to his hands, and gazing at him with looks of silent
love.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookname.com