0% found this document useful (0 votes)
35 views24 pages

Swift Programming Language Guide

The document is an introduction to the Swift programming language, detailing its features, syntax, and capabilities for developing applications on Apple platforms. It highlights Swift's modern programming patterns, interoperability with Objective-C, and user-friendly design for both new and experienced programmers. The guide includes examples of basic programming tasks, flow control, functions, closures, and object-oriented programming concepts in Swift.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views24 pages

Swift Programming Language Guide

The document is an introduction to the Swift programming language, detailing its features, syntax, and capabilities for developing applications on Apple platforms. It highlights Swift's modern programming patterns, interoperability with Objective-C, and user-friendly design for both new and experienced programmers. The guide includes examples of basic programming tasks, flow control, functions, closures, and object-oriented programming concepts in Swift.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

The

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

The Swift Programming Language


This book is a translation of "The Swift Programming Language", which is located at swift.org.

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 feels familiar to Objective-Cbookmark31 developers. It adopts the readability of named


parameters from Objective-C, as well as the dynamic object model. Provides seamless access to
existing Cocoa frameworks bookmark14and full interoperability with Objective-C. Building on this
foundation, Swift introduces many new concepts and unifies the procedural and object-oriented
aspects of the language.

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!")

If you've written code in C or Objective-Cbookmark31, this syntax should be familiar to you. In


Swift, this line of code is a complete program. You don't need to import a library for input/output
functionality or text handling. Code written in the global context is used as an entry point for the
application, so you don't need a main() function, nor do you need to write a semicolon at the end
of each statement.

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

Creates a constant with an explicit type of Float and a value of 4 .

Values are never implicitly converted to another type. If you need to convert a value to another
type, explicitly instantiate the desired type.

let tag: "The width is "


let width = 94
let labelWidth = label + String(width)

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" ]

professions["Jayne"] = "Public Relations"

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.

myShoppingList = [] professions = [:]

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.

let individualScores = [75, 43, 103, 87, 12]

var teamScore = 0

for score in individualScores {

if score > 50 {teamScore += 3 } else {


teamScore += 1
}

}
print(teamScore)

In an if statement, the conditional statement bookmark16should be a boolean expression, which


means that code like if score { ... } is an error but not an implicit comparison to zero. You can use if
and let together to work with values that might be missing. These values are represented as
optional. An optional value contains a nil (null) value to represent that a value is missing. Type a
question mark ( ? ) after the value type to mark it as optional.

var optionalText: String? = "Hello" print(optionaltext == nil)

var nameOptional: String? = "John Appleseed" var greeting = "Hello!"


if let name = optionalName { greeting = "Hello, \(name)"
}

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.

let nickname: String? = nil


let fullName: String = "John Appleseed"
let informalGreetings = "Hello \(nickname ?? fullName)"

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

let vegetal = "red chili"


vegetable switch {
case "celery":
print("Add some raisins and have a bite.")
case "cucumber", "watercress":
print("That would make a nice dish.")
case let x where x.hasPrefix("chilli")
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}

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)

Functions and Closures


Use func to declare a function. Calls a function by appending a list of arguments in parentheses to
the function name. Use -> to separate parameter names and types from the function's return type.

func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)."
}

greet("Bob", day: "Tuesday")

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

for score in scores { if score > max { max = score


} else if score < min { min = score
}
sum += score
}

return (min, max, sum)


}
let statistics = calculateStatistics([5, 3, 100, 3, 9])
print(stats.sum)
print(stats.2)

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.

func returnFifteen() -> { var y = 10 func add() { y += 5


} add() return y }
returnFifteen()

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)

A function can take another function as one of its arguments.

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
}

func lessThanTen(number: Int) -> Bool { return number < 10


}
var numbers = [20, 19, 7, 12]
hasAnyPair(numbers, condition: lessThanTen)

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.

let numerosMapeados = numeros.map({ numero in 3 * numero }) print(numerosMapeados)

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.

let numerosOrdenados = numeros.sort { 0$ > $1 } print(numerosOrdenados)

Objects and Classes


Use class followed by the class name bookmark12to create a class. A property declaration in a
class is written in the same way as the declaration of a constant or variable, except that it is in
the context of the class. Method and function declarations are written the same way.

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.

var figure = Figure() figure.numberOfSides = 7


var FigureDescription = figure.simpleDescription()

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.

class NamedFigure { var numberOfSides: Int = 0 var name: String

init(name: String) { self.name = name }

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

. Redefining a method by accident, without checking override , is detected by the compiler as an


error. The compiler also detects overridden methods that do not actually redefine any methods in their
superclass.

class Square: NamedFigure {


var sideWidth: Double

init(sideWidth: Double, name: String) { self.sideWidth = sideWidth super.init(name: name) numberOfSides = 4


}

A Guide to Swift 14
The Swift Programming Language

func area() -> Double { return sideWidth * sideWidth


}

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

class EquilateralTriangle: NamedFigure {


var sideWidth: Double = 0.0

init(sideWidth: Double, name: String) { self.sideWidth = sideWidth super.init(name: name) numberOfSides = 4


}

var perimeter: Double { get {


return 3.0 * SideWidth } set {
sideWidth = newValue / 3.0 }
}

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:

1. Assign the value of the properties that the subclass declares.


2. Call the superclass initializer.
3. Change the value of properties defined by the superclass. Any additional work requiring the
use of methods, consultants or modifiers may be used at this time.

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
}

var square: Square {


willSet {
triangle.sideWidth = newValue.sideWidth
}

A Guide to Swift 16
The Swift Programming Language

init(size: Double, name: String) {


square = Square(sideWidth: size, name: name)
triangle = EquilateralTriangle(sideWidth: size, name: name)
}

}
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 squareOptional: Square? =Square(sideWidth: 2.5, name: "optionalSquarebookmark32") let sideWidth =


optionalSquare?.sideWidth

Enumerations and Structures


Use enum to create an enumeration. Like classes and other named types, enumerations can have
methods associated with them.

enum Range: Int {


case As = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King
func simpledescription() -> String { switch self { case .As:
return "as"
case .Jack: return "jack" case .Queen:
return "queen"
case .King:
return "king" default:
return String(self.rawValue) }
}

}
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.

1.1. About Swift

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).

1.2. A Guide to Swift

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.

1.2. A Guide to Swift

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.

1.2. A Guide to Swift

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.

1.2. A Guide to Swift

Closing
(Clousure, Block) A function evaluated in an environment that contains one or more variables
dependent on another environment.

1.2. A Guide to Swift

Cocoa
The application development framework for the OS X (formerly known as the Macintosh)
platform.

1.1. About Swift

Cocoa Touch
The framework for developing applications for the iOS platform (the operating system for iPhone,
iPod, and iPad).

1.1. About Swift

Conditional
A statement or group of statements that may or may not be executed depending on the value of a
condition.

1.2. A Guide to Swift

Consultant
(Getter) Method that returns the value of a property of an object.

1.2. A Guide to Swift

Automatic Reference Counting

Glossary 19
The Swift Programming Language

(Automatic Reference Counting, ARC) In Objective-C and Swift programming, Automatic


Reference Counting is a memory management enhancement where the burden of maintaining an
object's reference count is transferred from the programmer to the compiler.

1.1. About Swift

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.

1.2. A Guide to Swift

Scrubber
(Debugger) A debugger is a program used to test and debug (remove) errors from other
programs.

1.1. About Swift

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.

1.2. A Guide to Swift

Entry and Exit


(Input/Output, I/O) A device that enables communication between an information processing
system, such as a computer, and the outside world, and possibly a human or another information
processing system.

1.3. A Guide to Swift

Foundation
The premier framework for developing apps for all Apple platforms.

Glossary 20
The Swift Programming Language

1.1. About Swift

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.

1.2. A Guide to Swift

Index
(Index) The number associated with an element in an array.

1.3. A Guide to Swift

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.

1.1. About Swift

Key
(Key) The text with which a value is associated in a dictionary.

1.2. A Guide to Swift

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

(Setter) Method that changes the value of a property of an object.

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.

1.2. A Guide to Swift

Integer
(Integer) An integer data type in computing is a data type that can represent a finite subset of the
integers.

1.2. A Guide to Swift

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.

1.1. About Swift 1.2. A Guide to Swift

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.

1.2. A Guide to Swift

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

1.1. About Swift

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.

1.1. About Swift

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.

1.1. About Swift

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.

1.1. About Swift

Swift
Multiparadigm programming language created by Apple focused on the development of
applications for its platforms.

1.1. About Swift 1.2. A Guide to Swift 1. Welcome to Swift 0. Introduction

Text
Known as "String" in English and most programming languages.

1.2. A Guide to Swift

Tuple

Glossary 23
The Swift Programming Language

(Tuple) Set of elements of different types that are stored consecutively in memory.

1.3. A Guide to Swift

Glossary 24

You might also like