Swift Programming Language Guide
Swift Programming Language Guide
Language of
Swift
Programming
5
Published with
Alsey Coleman Miller
GitBook
5
The Swift Programming Language
table of Contents
Welcome to Swift 5
About Swift 6
A Guide to Swift 8
Glossary 20
Glossary
3
The Swift Programming Language
Links
• swiftespanol.com
• GitBooks
• GitHub
Introduction 4
The Swift Programming Language
Welcome to Swift
Welcome to Swift 5
The Swift Programming Language
About Swift
Swift is a new programming language for iOS, OS X, watchOS, and tvOS applications that is built
on the best of C and Objective-C, without the restrictions of C compatibility. Swift adopts safe
programming patterns and adds modern features to make the process easier, more flexible, and
more fun. The new, clean implementation of Swift, supported by the Cocoa bookmark14and
Cocoa Touch frameworks, provides an opportunity to reimagine how software development
works.
The process of creating Swiftbookmark37 has been going on for several years. Apple laid the
foundation for this by improving our compiler, debugger, and framework infrastructure. We have
simplified memory management by creating Automatic Reference Counting. Our frameworks,
built on the solid foundation of Foundation and Cocoa, have been modernized and standardized.
Objective-C itself has evolved to support closures, collection literals, and modules, enabling
frameworks to adopt modern language technologies without hindrance. Thanks to this work, we
can introduce a new development language for the future of software development for Apple
platforms.
Swift is friendly for new programmers. It is the first industrial-grade systems programming
language that is as expressive and enjoyable as an interpreted language. Supports playgrounds,
an innovative feature that opens the door to experimentation with Swift code and allows you to
see the results immediately, without having to compile and run the application.
Swift combines the best philosophy of modern languages with the wisdom of Apple's extensive
engineering culture. The compiler is optimized for best performance, and the language for
optimal development, without compromising either. It is designed to scale from a hello world
implementation to an entire operating system. All of this makes Swift a safe investment for
developers and Apple.
It's also a fantastic way to write iOS, OS X, watchOS, and tvOS apps, and it will continue to
evolve with new features and capabilities. Our goals for Swift are ambitious. We can't wait to see
what you can create with it.
About Swift 6
The Swift Programming Language
A Guide to Swift
Tradition suggests that the first program in a new development language should print the words
"Hello, world!" on the screen. In Swift, this can be done with a single line of code:
print("Hello, world!")
This guide gives you enough information to start writing code in Swift by showing you how to
implement a variety of programming tasks. Don't worry if you didn't understand something,
everything mentioned here is explained in detail in the rest of the book.
Simple Values
Let is used to create a constant and var is used to create a variable. The value of a constant does
not need to be known at compile time, but it must be assigned a value exactly once. This means
that you can use constants to name a value that is determined once and use it in many places.
var myVariable = 42
myVariable = 50
let myConstant = 42
A constant or variable should have the same type of value that you want to assign to it. However,
you don't need to write it explicitly all the time. Providing a value when you create the constant or
variable allows the compiler to deduce its type. In the example above, the compiler deduces that
myVariable is an integer because its initial value is also an integer.
If the initial value does not provide enough information (or if there is no initial value), specify the
type by writing it after the variable, separated by a colon as shown below.
let implicitInteger = 70
let doubleImplicit = 70.0
let doubleExplicit: Double = 70
Experiment
A Guide to Swift 7
The Swift Programming Language
Values are never implicitly converted to another type. If you need to convert a value to another
type, explicitly instantiate the desired type.
Experiment
Try removing the conversion to String from the last line. What error do you see?
There is a simpler way to include multiple values in text: Write the value in parentheses, and type
a backslash ( \ ) before them. For example:
let apples = 3
let oranges = 5
let manazanaSummary = "I have \(manzanas) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
Experiment
Use \() to include a floating-point calculation in text and to include someone's name in a
greeting.
Create arrays and dictionaries using square brackets ( [] ) and access their elements by writing
the index or key in square brackets. A comma is allowed after the first element.
var myShoppingList = ["catfish", "water", "tulips", "blue paint"] myShoppingList[1] = "water bottle"
var professions = [
"Malcolm": "Captain",
"Kaylee": "Mechanic" ]
If the type information can be deduced, you can write an empty array as [] and an empty
dictionary as [:] : This might occur, for example, when you create a new value for a variable or
pass an argument to a function.
Flow Control
A Guide to Swift 8
The Swift Programming Language
Use if and switch to create conditional statements, and use for-in , for , while , and repeat to make a
loop. The parentheses closing the condition or loop are optional, but the braces above the body
are required.
var teamScore = 0
}
print(teamScore)
Experiment
Changes optionalText to nil . What greeting do you get? Add an else clause that assigns another
greeting if optionalName is nil .
If the optional value bookmark32is nil , the conditional value is false and the code in the braces is
skipped. Otherwise, the optional value bookmark32is unwrapped and assigned to the constant
after let , which makes the unwrapped value available within the code block.
Another way to handle optional values is to provide a default value using the ?? operator. . If the
optional value is missing, the default value is used instead.
switch supports any data type and a wide variety of comparison operations: they are not limited to
integers and equality tests.
A Guide to Swift 9
The Swift Programming Language
Experiment
Try removing the default case ( default: ). What error are you getting?
Note how let can be used in a pattern to assign the value that matched that part of the pattern to a
constant.
After executing the code inside the matching case, the program exits the switch statement.
Execution does not continue to the next case, so there is no need to explicitly break each case.
You can use for-in to iterate over items in a dictionary by providing a pair of names to use for each
bookmark26key-value pair.
Dictionaries are an unordered collection, so their keys and values are iterated in an arbitrary
order.
let interestingNumbers = [
"Cousin": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25], ] var largest = 0
for (type, numbers) in InterestingNumbers { for number in numbers {
if number > largest { largest = number }
}
}
print(larger)”
Experiment
Add another variable to record what type of number was the largest, as well as its value.
Use while to repeat a block of code until a condition changes. The condition of a loop can be at the
end as well, ensuring that the loop is executed at least once.
var n = 2
while n < 100 {
n=n*2
}
print(n) var m = 2 repeat {
A Guide to Swift 10
The Swift Programming Language
m=m*2
} while m < 100 print(m)
You can store an index in a loop, by using ..< to make a range of indices, or by explicit
initialization, condition, and increment. These two cycles do the same thing:
var firstCycle = 0
for i in 0..<4 { firstCycle += i
}
print(firstCycle)
var secondCycle = 0
for var i = 0; i < 4; ++i { secondCycle += i
}
print(secondCycle)
func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)."
}
Experiment
Remove the dia parameter. Add a parameter that includes today's lunch in the greeting.
Use a tuple to make a value composite: for example, to return multiple values from a function.
Elements of a tuple can be referred to by name or number.
A Guide to Swift 11
The Swift Programming Language
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { var min = scores[0] var max = scores[0] var sum = 0
Functions can also take a varying number of arguments, collecting them in an array.
func sum(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number
} return sum
}
addition()
sum(42, 597, 12)
Experiment
Write a function that calculates the average value of its arguments.
Functions can be nested. Nested functions have access to variables that were declared in the
outer function. You can use nested functions to organize the code in a function that is long or
complex.
Functions are a type of first class. This means that a function can return another function as its
value.
func createIncrementer() -> ((Int) -> (Int)) { func addOne(number: Int) -> Int { return 1 + number
} return addOne
}
var increment = createIncrementer() increment(7)
func hasSomeCouple(list: [Int], condition: (Int -> Bool)) -> Bool { for element in list {
if condition(element) { return true
A Guide to Swift 12
The Swift Programming Language
return false
}
Functions are actually a special case of closures: blocks of code that can be called later. Code in
a closure has access to things like variables and functions that were available in the context
where it was created, even if the closure is being executed in another context: you've already
seen an example of this with nested functions. You can write an unnamed closure by enclosing
code in braces ( {} ). Use in to separate the arguments and return type from the function body.
numbers.map({ (number: Int) -> Int in let result = 3 * number return result
})
Experiment
Rewrite the closure so that it returns zero for every odd number.
You have several options for writing closings more concisely. When the type of the closure is
already known, as is a callback for a delegate, you can omit the type of the parameters, return
value, or both. Single-statement closures implicitly return the value of their single statement.
You can refer to parameters by number instead of their name, this strategy is especially useful in
short closures. A closure passed as a last argument may appear immediately after the
parentheses. When a closure is the only argument to a function, you can omit the parentheses
entirely.
A Guide to Swift 13
The Swift Programming Language
class Figure {
var numberOfSides = 0
func SimpleDescription() -> String { return "A figure with \(numberOfSides) sides." } }
Experiment
Add a constant property with let and add another property that takes one argument.
Create an instance of a class by placing parentheses after the class name. Use periods ( . ) to
access the instance's properties and methods.
This version of the Figure class is missing something important: an initializer to configure the class
when an instance is created. Use init to create one.
func SimpleDescription() -> String { return "A figure with \(numberOfSides) sides." } }
Note how self is used to distinguish the name property from the argument to the initializer also called
name . Its arguments to the initializer are passed as a function call when you create an instance of
the class. Every property needs a value assigned, either in its declaration (as with numberOfSides )
or in the initializer (as with name ).
Use deinit to create the deinitializer if you need to perform cleanup operations when the object is
deallocated.
Subclasses include the name of their superclass (or parent class) after the name of their class,
separated by a colon. There is no requirement for classes to be subclasses of any parent class,
so you can include or omit a superclass depending on your needs.
Methods in a subclass that override the implementation of the superclass are marked with override
A Guide to Swift 14
The Swift Programming Language
override func SimpleDescription() -> String { return "A square with \(SideWidth) width of sides."
}
}
let test = Square(sideWidth: 5.2, name: "my test square") test.area()
test.simpledescription()
Experiment
Make another subclass of NamedFigure called Circle that takes a radius and a name as arguments
to its initializer. Implement the area() and descriptionSimple() methods in the Circle class.
In addition to simple properties that are stored, properties can have getter and setter methods.
A Guide to Swift 15
The Swift Programming Language
override func SimpleDescription() -> String { return "An equilateral triangle with \(SideWidth) side width."
}
}
var triangle = EquilateralTriangle(sideWidth: 3.1, name: "a triangle") print(triangle. perimeter) triangle. perimeter = 9.9
print(triangle. sideWidth)
In the perimeter consultant, the new value has the implicit name newValue . You can provide an
explicit name in the parentheses after set .
Note how the initializer for the EquilateralTriangle class has three different steps:
If you don't need to calculate the property value, but still need to provide code that is executed
after a new value is assigned, use willSet and didSet .
The code you provide is executed when the value changes outside of an initializer. For example,
the following class ensures that the width of the sides of a triangle always equals the width of its
square.
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideWidth = newValue.sideWidth
}
A Guide to Swift 16
The Swift Programming Language
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test figure")
print(triangleAndSquare.square.sideWidth)
print(triangleAndSquare.triangle.sideWidth)
triangleAndSquare.square = Square(sideWidth: 50, name: "larger square") print(triangleAndSquare.triangle.sideWidth)
.------------------------------------------------------------------------------------------------------------------------------------- -------------,
When working with optional values, you can write ? before operations such as methods,
properties, and subscripts. If the value before ? is nil , everything after the ? is ignored and the
value of the entire expression is nil . Otherwise, the optional value bookmark32is unwrapped, and
everything after the ? acts on the developed value. In both cases, the value of the expression is
an optional value.
}
let as = Range.As
let asValue = as.rawValue
A Guide to Swift 17
The Swift Programming Language
Glossary
Apple
Apple Inc. is an American multinational corporation that designs and produces electronic
equipment and software, headquartered in Cupertino, California, United States. Among the
company's best-known hardware products are Macintosh computers, the iPod, the iPhone and
the iPad.
Arrangement
(Array) In programming, a matrix, vector or array is also called a continuous storage area that
contains a series of elements of the same type, the elements of the matrix. From a logical point of
view, a matrix can be seen as a set of elements ordered in a row (or rows and columns if it had
two dimensions).
Boolean
(Boolean, Bool) The logical or boolean data type is in computing that which can represent binary
logic values, that is, 2 values, values that normally represent false or true.
Cycle
(Loop) A loop or cycle, in programming, is a statement that is repeatedly performed on an
isolated piece of code, until the condition assigned to said loop is no longer met.
Class
(Class) A template for creating data objects according to a predefined model. Classes are used
to represent entities or concepts, like nouns in language. Each class is a model that defines a set
Glossary 18
The Swift Programming Language
of variables - the state, and appropriate methods for operating on that data - the behavior. Each
object created from the class is called an instance of the class.
Closing
(Clousure, Block) A function evaluated in an environment that contains one or more variables
dependent on another environment.
Cocoa
The application development framework for the OS X (formerly known as the Macintosh)
platform.
Cocoa Touch
The framework for developing applications for the iOS platform (the operating system for iPhone,
iPod, and iPad).
Conditional
A statement or group of statements that may or may not be executed depending on the value of a
condition.
Consultant
(Getter) Method that returns the value of a property of an object.
Glossary 19
The Swift Programming Language
Context
(Scope) The minimum set of data used by a task that must be saved to allow its interruption at a
given time, and a subsequent continuation from the point where it was interrupted at a future
time.
Scrubber
(Debugger) A debugger is a program used to test and debug (remove) errors from other
programs.
Dictionary
(Dictionary) A dictionary (also associative container, map, mapper, hash, associative vector, finite
map, lookup table) is an abstract data type consisting of a collection of unique keys and a
collection of values, with a one-to-one association.
Foundation
The premier framework for developing apps for all Apple platforms.
Glossary 20
The Swift Programming Language
Function
(Function) A function (also called a subroutine, subprogram, procedure, routine or method) is a
segment of code separate from the main block and that can be called at any time from it or
another block.
Index
(Index) The number associated with an element in an array.
Interpreted Language
(Scripting language) Language that uses an interpreter instead of a compiler. Interpreters differ
from compilers or assemblers in that while compilers or assemblers translate a program from its
description in a programming language into the machine code of the system, interpreters only
perform the translation as it is needed, typically instruction by instruction, and normally do not
save the result of such translation.
Key
(Key) The text with which a value is associated in a dictionary.
Framework
(Framework) A defined supporting conceptual and technological structure, usually with specific
software modules or artifacts, that can serve as a basis for the organization and development of
software.
Modifier
Glossary 21
The Swift Programming Language
Method
(Method) A function whose code is defined in a class and can belong to either a class, as is the
case with class or static methods, or to an object, as is the case with instance methods. The
difference between a function and a method is that the latter, being associated with a particular
object or class, can access and modify the private data of the corresponding object in a way that
is consistent with the desired behavior for the object.
Integer
(Integer) An integer data type in computing is a data type that can represent a finite subset of the
integers.
Objective-C
Objective-C is an object-oriented programming language created as a superset of C to implement
an object model similar to that of Smalltalk.
Optional
(Optional) An optional type is a polymorphic type that represents the encapsulation of an optional
value; for example, it is used as the return type of functions that may or may not return a
meaningful value when applied. It consists of either an empty constructor (named "None" or
"Nothing"), or a constructor that encapsulates the original data type A (named "Just A" or "Some
A"). Outside of functional programming, these are known as nullable types.
Object Oriented
Object-oriented programming (OOP) is a programming paradigm that uses objects in their
interactions to design computer applications and programs.
Glossary 22
The Swift Programming Language
Playgrounds
Swift environment that allows you to use the language as if it were interpreted and not compiled.
It allows programmers to experiment with Swift code and see the results immediately, without the
expense of compiling and running the application.
Procedural
Procedural programming is a programming paradigm. This technique consists of relying on a
very small number of repeated expressions, encompassing them all in a procedure or function
and calling it every time it needs to be executed.
Software
Logical equipment or logical support of a computer system, which includes the set of necessary
logical components that make it possible to carry out specific tasks, as opposed to the physical
components that are called hardware.
Swift
Multiparadigm programming language created by Apple focused on the development of
applications for its platforms.
Text
Known as "String" in English and most programming languages.
Tuple
Glossary 23
The Swift Programming Language
(Tuple) Set of elements of different types that are stored consecutively in memory.
Glossary 24