Swift Programming Language 57
Swift Programming Language 57
Swift code is compiled and optimized to get the most out of modern
hardware. The syntax and standard library have been designed
based on the guiding principle that the obvious way to write your code
Swift has been years in the making, and it continues to evolve with
new features and capabilities. Our goals for Swift are ambitious. We
can’t wait to see what you create with it.
This book describes Swift 5.7, the default version of Swift that’s
included in Xcode 14. You can use Xcode 14 to build targets that are
written in either Swift 5.7, Swift 4.2, or Swift 4.
When you use Xcode 14 to build Swift 4 and Swift 4.2 code, most
Swift 5.7 functionality is available. That said, the following changes
are available only to code that uses Swift 5.7 or later:
1 print("Hello, world!")
2 // Prints "Hello, world!"
This tour gives you enough information to start writing code in Swift
by showing you how to accomplish a variety of programming tasks.
Don’t worry if you don’t understand something—everything
introduced in this tour is explained in detail in the rest of this book.
NOTE
On a Mac with Xcode installed, or on an iPad with Swift Playgrounds, you can
open this chapter as a playground. Playgrounds allow you to edit the code
listings and see the result immediately.
Download Playground
Simple Values
1 var myVariable = 42
2 myVariable = 50
3 let myConstant = 42
A constant or variable must have the same type as the value you
want to assign to it. However, you don’t always have to write the type
explicitly. Providing a value when you create a constant or variable
lets the compiler infer its type. In the example above, the compiler
infers that myVariable is an integer because its initial value is an
integer.
If the initial value doesn’t provide enough information (or if there isn’t
an initial value), specify the type by writing it after the variable,
separated by a colon.
1 let implicitInteger = 70
2 let implicitDouble = 70.0
3 let explicitDouble: Double = 70
EXPERIMENT
EXPERIMENT
Try removing the conversion to String from the last line. What error do you
get?
1 let apples = 3
2 let oranges = 5
3 let appleSummary = "I have \(apples) apples."
4 let fruitSummary = "I have \(apples + oranges)
pieces of fruit."
EXPERIMENT
Use three double quotation marks (""") for strings that take up
multiple lines. Indentation at the start of each quoted line is removed,
as long as it matches the indentation of the closing quotation marks.
For example:
Create arrays and dictionaries using brackets ([]), and access their
elements by writing the index or key in brackets. A comma is allowed
after the last element.
1 fruits.append("blueberries")
2 print(fruits)
1 fruits = []
2 occupations = [:]
Control Flow
Use if and switch to make conditionals, and use for-in, while, and
repeat-while to make loops. Parentheses around the condition or
loop variable are optional. Braces around the body are required.
You can use if and let together to work with values that might be
missing. These values are represented as optionals. An optional
value either contains a value or contains nil to indicate that a value
is missing. Write a question mark (?) after the type of a value to mark
the value as optional.
EXPERIMENT
Change optionalName to nil. What greeting do you get? Add an else clause
that sets a different greeting if optionalName is nil.
If the optional value is nil, the conditional is false and the code in
braces is skipped. Otherwise, the optional value is unwrapped and
assigned to the constant after let, which makes the unwrapped value
available inside the block of code.
You can use a shorter spelling to unwrap a value, using the same
name for that unwrapped value.
1 if let nickname {
2 print("Hey, \(nickname)")
3 }
Notice how let can be used in a pattern to assign the value that
matched the pattern to a constant.
After executing the code inside the switch case that matched, the
program exits from the switch statement. Execution doesn’t continue
to the next case, so you don’t need to explicitly break out of the
switch at the end of each case’s code.
EXPERIMENT
Replace the _ with a variable name, and keep track of which kind of number
was the largest.
1 var total = 0
2 for i in 0..<4 {
3 total += i
4 }
5 print(total)
6 // Prints "6"
Use ..< to make a range that omits its upper value, and use ... to
make a range that includes both values.
EXPERIMENT
Remove the day parameter. Add a parameter to include today’s lunch special
in the greeting.
Functions are a first-class type. This means that a function can return
another function as its value.
You have several options for writing closures more concisely. When a
closure’s type is already known, such as the callback for a delegate,
you can omit the type of its parameters, its return type, or both. Single
statement closures implicitly return the value of their only statement.
EXPERIMENT
Add a constant property with let, and add another method that takes an
argument.
Notice how self is used to distinguish the name property from the
name argument to the initializer. The arguments to the initializer are
passed like 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).
Make another subclass of NamedShape called Circle that takes a radius and
a name as arguments to its initializer. Implement an area() and a
simpleDescription() method on the Circle class.
In the setter for perimeter, the new value has the implicit name
newValue. You can provide an explicit name in parentheses after set.
Notice that the initializer for the EquilateralTriangle class has three
different steps:
If you don’t need to compute the property but still need to provide
code that’s run before and after setting a new value, use willSet and
didSet. The code you provide is run any time the value changes
outside of an initializer. For example, the class below ensures that the
side length of its triangle is always the same as the side length of its
square.
When working with optional values, you can write ? before operations
like methods, properties, and subscripting. If the value before the ? is
nil, everything after the ? is ignored and the value of the whole
expression is nil. Otherwise, the optional value is unwrapped, and
everything after the ? acts on the unwrapped value. In both cases, the
value of the whole expression is an optional value.
Write a function that compares two Rank values by comparing their raw
values.
EXPERIMENT
Add a color() method to Suit that returns “black” for spades and clubs, and
returns “red” for hearts and diamonds.
Notice the two ways that the hearts case of the enumeration is
referred to above: When assigning a value to the hearts constant, the
enumeration case Suit.hearts is referred to by its full name because
the constant doesn’t have an explicit type specified. Inside the switch,
the enumeration case is referred to by the abbreviated form .hearts
EXPERIMENT
Notice how the sunrise and sunset times are extracted from the
ServerResponse value as part of matching the value against the
switch cases.
1 struct Card {
2 var rank: Rank
3 var suit: Suit
4 func simpleDescription() -> String {
5 return "The \(rank.simpleDescription()) of \
(suit.simpleDescription())"
6 }
7 }
8 let threeOfSpades = Card(rank: .three, suit:
.spades)
9 let threeOfSpadesDescription =
threeOfSpades.simpleDescription()
EXPERIMENT
Write a function that returns an array containing a full deck of cards, with one
card of each combination of rank and suit.
Concurrency
Use async to mark a function that runs asynchronously.
1 Task {
2 await connectUser(to: "primary")
3 }
4 // Prints "Hello Guest, user ID 97"
1 protocol ExampleProtocol {
2 var simpleDescription: String { get }
3 mutating func adjust()
4 }
EXPERIMENT
EXPERIMENT
Write an extension for the Double type that adds an absoluteValue property.
You can use a protocol name just like any other named type—for
example, to create a collection of objects that have different types but
that all conform to a single protocol. When you work with values
whose type is a protocol type, methods outside the protocol definition
aren’t available.
Error Handling
You represent errors using any type that adopts the Error protocol.
Use throw to throw an error and throws to mark a function that can
throw an error. If you throw an error in a function, the function returns
immediately and the code that called the function handles the error.
There are several ways to handle errors. One way is to use do-catch.
Inside the do block, you mark code that can throw an error by writing
try in front of it. Inside the catch block, the error is automatically
given the name error unless you give it a different name.
1 do {
2 let printerResponse = try send(job: 1040,
toPrinter: "Bi Sheng")
3 print(printerResponse)
4 } catch {
5 print(error)
6 }
7 // Prints "Job sent"
EXPERIMENT
You can provide multiple catch blocks that handle specific errors. You
write a pattern after catch just as you do after case in a switch.
EXPERIMENT
Add code to throw an error inside the do block. What kind of error do you need
to throw so that the error is handled by the first catch block? What about the
second and third blocks?
Generics
Write a name inside angle brackets to make a generic function or
type.
EXPERIMENT
1 let maximumNumberOfLoginAttempts = 10
2 var currentLoginAttempt = 0
NOTE
Type Annotations
You can provide a type annotation when you declare a constant or
variable, to be clear about the kind of values the constant or variable
can store. Write a type annotation by placing a colon after the
constant or variable name, followed by a space, followed by the name
of the type to use.
The colon in the declaration means “…of type…,” so the code above
can be read as:
The phrase “of type String” means “can store any String value.”
Think of it as meaning “the type of thing” (or “the kind of thing”) that
can be stored.
welcomeMessage = "Hello"
You can define multiple related variables of the same type on a single
line, separated by commas, with a single type annotation after the
final variable name:
NOTE
It’s rare that you need to write type annotations in practice. If you provide an
initial value for a constant or variable at the point that it’s defined, Swift can
almost always infer the type to be used for that constant or variable, as
described in Type Safety and Type Inference. In the welcomeMessage
example above, no initial value is provided, and so the type of the
welcomeMessage variable is specified with a type annotation rather than being
inferred from an initial value.
1 let π = 3.14159
2 let 你好 = "你好世界"
3 let 🐶 🐮 = "dogcow"
Constant and variable names can’t contain whitespace characters,
mathematical symbols, arrows, private-use Unicode scalar values, or
line- and box-drawing characters. Nor can they begin with a number,
although numbers may be included elsewhere within the name.
NOTE
If you need to give a constant or variable the same name as a reserved Swift
keyword, surround the keyword with backticks (`) when using it as a name.
However, avoid using keywords as names unless you have absolutely no
choice.
NOTE
All options you can use with string interpolation are described in String
Interpolation.
// This is a comment.
Integers
Integers are whole numbers with no fractional component, such as 42
and -23. Integers are either signed (positive, zero, or negative) or
unsigned (positive or zero).
Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit
forms. These integers follow a naming convention similar to C, in that
an 8-bit unsigned integer is of type UInt8, and a 32-bit signed integer
is of type Int32. Like all types in Swift, these integer types have
capitalized names.
Integer Bounds
You can access the minimum and maximum values of each integer
type with its min and max properties:
Int
In most cases, you don’t need to pick a specific size of integer to use
in your code. Swift provides an additional integer type, Int, which has
the same size as the current platform’s native word size:
Unless you need to work with a specific size of integer, always use
Int for integer values in your code. This aids code consistency and
interoperability. Even on 32-bit platforms, Int can store any value
between -2,147,483,648 and 2,147,483,647, and is large enough for
many integer ranges.
UInt
Swift also provides an unsigned integer type, UInt, which has the
same size as the current platform’s native word size:
Use UInt only when you specifically need an unsigned integer type with the
same size as the platform’s native word size. If this isn’t the case, Int is
preferred, even when the values to be stored are known to be nonnegative. A
consistent use of Int for integer values aids code interoperability, avoids the
need to convert between different number types, and matches integer type
inference, as described in Type Safety and Type Inference.
Floating-Point Numbers
Floating-point numbers are numbers with a fractional component,
such as 3.14159, 0.1, and -273.15.
NOTE
1 let pi = 3.14159
2 // pi is inferred to be of type Double
Swift always chooses Double (rather than Float) when inferring the
type of floating-point numbers.
Numeric Literals
Integer literals can be written as:
1 let decimalInteger = 17
2 let binaryInteger = 0b10001 // 17 in binary
notation
3 let octalInteger = 0o21 // 17 in octal
notation
4 let hexadecimalInteger = 0x11 // 17 in
hexadecimal notation
Use other integer types only when they’re specifically needed for the
task at hand, because of explicitly sized data from an external source,
or for performance, memory usage, or other necessary optimization.
Using explicitly sized types in these situations helps to catch any
accidental value overflows and implicitly documents the nature of the
data being used.
Because each numeric type can store a different range of values, you
must opt in to numeric type conversion on a case-by-case basis. This
opt-in approach prevents hidden conversion errors and helps make
type conversion intentions explicit in your code.
1 let three = 3
2 let pointOneFourOneFiveNine = 0.14159
3 let pi = Double(three) + pointOneFourOneFiveNine
4 // pi equals 3.14159, and is inferred to be of type
Double
Here, the value of the constant three is used to create a new value of
type Double, so that both sides of the addition are of the same type.
Without this conversion in place, the addition would not be allowed.
NOTE
The rules for combining numeric constants and variables are different from the
rules for numeric literals. The literal value 3 can be added directly to the literal
value 0.14159, because number literals don’t have an explicit type in and of
themselves. Their type is inferred only at the point that they’re evaluated by
the compiler.
Type Aliases
Type aliases define an alternative name for an existing type. You
define type aliases with the typealias keyword.
Type aliases are useful when you want to refer to an existing type by
a name that’s contextually more appropriate, such as when working
with data of a specific size from an external source:
Once you define a type alias, you can use the alias anywhere you
might use the original name:
Booleans
Swift has a basic Boolean type, called Bool. Boolean values are
referred to as logical, because they can only ever be true or false.
Swift provides two Boolean constant values, true and false:
Boolean values are particularly useful when you work with conditional
statements such as the if statement:
1 let i = 1
2 if i {
3 // this example will not compile, and will
report an error
4 }
1 let i = 1
2 if i == 1 {
3 // this example will compile successfully
4 }
Tuples
Tuples group multiple values into a single compound value. The
values within a tuple can be of any type and don’t have to be of the
same type as each other.
The (404, "Not Found") tuple groups together an Int and a String
to give the HTTP status code two separate values: a number and a
human-readable description. It can be described as “a tuple of type
(Int, String)”.
You can create tuples from any permutation of types, and they can
contain as many different types as you like. There’s nothing stopping
you from having a tuple of type (Int, Int, Int), or (String, Bool),
or indeed any other permutation you require.
If you only need some of the tuple’s values, ignore parts of the tuple
with an underscore (_) when you decompose the tuple:
You can name the individual elements in a tuple when the tuple is
defined:
If you name the elements in a tuple, you can use the element names
to access the values of those elements:
NOTE
Tuples are useful for simple groups of related values. They’re not suited to the
creation of complex data structures. If your data structure is likely to be more
complex, model it as a class or structure, rather than as a tuple. For more
information, see Structures and Classes.
Optionals
You use optionals in situations where a value may be absent. An
optional represents two possibilities: Either there is a value, and you
can unwrap the optional to access that value, or there isn’t a value at
all.
The example below uses the initializer to try to convert a String into
an Int:
Because the initializer might fail, it returns an optional Int, rather than
an Int. An optional Int is written as Int?, not Int. The question mark
indicates that the value it contains is optional, meaning that it might
contain some Int value, or it might contain no value at all. (It can’t
contain anything else, such as a Bool value or a String value. It’s
either an Int, or it’s nothing at all.)
NOTE
You can’t use nil with non-optional constants and variables. If a constant or
variable in your code needs to work with the absence of a value under certain
conditions, always declare it as an optional value of the appropriate type.
NOTE
1 if convertedNumber != nil {
2 print("convertedNumber contains some integer
value.")
3 }
4 // Prints "convertedNumber contains some integer
value."
Once you’re sure that the optional does contain a value, you can
access its underlying value by adding an exclamation point (!) to the
end of the optional’s name. The exclamation point effectively says, “I
know that this optional definitely has a value; please use it.” This is
known as forced unwrapping of the optional’s value:
1 if convertedNumber != nil {
2 print("convertedNumber has an integer value of \
(convertedNumber!).")
3 }
4 // Prints "convertedNumber has an integer value of
123."
Optional Binding
You use optional binding to find out whether an optional contains a
value, and if so, to make that value available as a temporary constant
or variable. Optional binding can be used with if and while
statements to check for a value inside an optional, and to extract that
value into a constant or variable, as part of a single action. if and
while statements are described in more detail in Control Flow.
1 if let myNumber {
2 print("My number is \(myNumber)")
3 }
4 // Prints "My number is 123"
You can use both constants and variables with optional binding. If you
wanted to manipulate the value of myNumber within the first branch of
the if statement, you could write if var myNumber instead, and the
value contained within the optional would be made available as a
variable rather than a constant. Changes you make to myNumber
1 if assumedString != nil {
2 print(assumedString!)
3 }
4 // Prints "An implicitly unwrapped optional string."
NOTE
Error Handling
1 do {
2 try canThrowAnError()
3 // no error was thrown
4 } catch {
5 // an error was thrown
6 }
1 let age = -3
2 assert(age >= 0, "A person's age can't be less than
zero.")
3 // This assertion fails because -3 isn't >= 0.
You can omit the assertion message—for example, when it would just
repeat the condition as prose.
assert(age >= 0)
Enforcing Preconditions
Use a precondition whenever a condition has the potential to be false,
but must definitely be true for your code to continue execution. For
example, use a precondition to check that a subscript isn’t out of
bounds, or to check that a function has been passed a valid value.
Swift supports the operators you may already know from languages
like C, and improves several capabilities to eliminate common coding
errors. The assignment operator (=) doesn’t return a value, to prevent
it from being mistakenly used when the equal to operator (==) is
intended. Arithmetic operators (+, -, *, /, % and so forth) detect and
disallow value overflow, to avoid unexpected results when working
with numbers that become larger or smaller than the allowed value
range of the type that stores them. You can opt in to value overflow
behavior by using Swift’s overflow operators, as described in
Overflow Operators.
Terminology
Operators are unary, binary, or ternary:
Assignment Operator
The assignment operator (a = b) initializes or updates the value of a
with the value of b:
1 let b = 10
2 var a = 5
3 a = b
4 // a is now equal to 10
If the right side of the assignment is a tuple with multiple values, its
elements can be decomposed into multiple constants or variables at
once:
1 if x = y {
2 // This isn't valid, because x = y doesn't
return a value.
3 }
This feature prevents the assignment operator (=) from being used by
accident when the equal to operator (==) is actually intended. By
making if x = y invalid, Swift helps you to avoid these kinds of
errors in your code.
Arithmetic Operators
Swift supports the four standard arithmetic operators for all number
types:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Remainder Operator
The remainder operator (a % b) works out how many multiples of b
will fit inside a and returns the value that’s left over (known as the
remainder).
NOTE
You can fit two 4s inside 9, and the remainder is 1 (shown in orange).
9 % 4 // equals 1
9 = (4 x 2) +1
-9 % 4 // equals -1
-9 = (4 x -2) + -1
The unary minus operator (-) is prepended directly before the value it
operates on, without any white space.
1 let minusSix = -6
2 let alsoMinusSix = +minusSix // alsoMinusSix equals
-6
NOTE
The compound assignment operators don’t return a value. For example, you
can’t write let b = a += 2.
Comparison Operators
Swift supports the following comparison operators:
Equal to (a == b)
Not equal to (a != b)
Swift also provides two identity operators (=== and !==), which you use to test
whether two object references both refer to the same object instance. For
more information, see Identity Operators.
You can compare two tuples if they have the same type and the same
number of values. Tuples are compared from left to right, one value at
a time, until the comparison finds two values that aren’t equal. Those
two values are compared, and the result of that comparison
determines the overall result of the tuple comparison. If all the
elements are equal, then the tuples themselves are equal. For
example:
NOTE
The Swift standard library includes tuple comparison operators for tuples with
fewer than seven elements. To compare tuples with seven or more elements,
you must implement the comparison operators yourself.
1 if question {
2 answer1
3 } else {
4 answer2
5 }
Here’s an example, which calculates the height for a table row. The
row height should be 50 points taller than the content height if the row
has a header, and 20 points taller if the row doesn’t have a header:
1 let contentHeight = 40
2 let hasHeader = true
3 let rowHeight = contentHeight + (hasHeader ? 50 :
20)
4 // rowHeight is equal to 90
The first example’s use of the ternary conditional operator means that
rowHeight can be set to the correct value on a single line of code,
which is more concise than the code used in the second example.
Nil-Coalescing Operator
The nil-coalescing operator (a ?? b) unwraps an optional a if it
contains a value, or returns a default value b if a is nil. The
expression a is always of an optional type. The expression b must
match the type that’s stored inside a.
The code above uses the ternary conditional operator and forced
unwrapping (a!) to access the value wrapped inside a when a isn’t
nil, and to return b otherwise. The nil-coalescing operator provides a
more elegant way to encapsulate this conditional checking and
unwrapping in a concise and readable form.
NOTE
1 userDefinedColorName = "green"
2 colorNameToUse = userDefinedColorName ??
defaultColorName
3 // userDefinedColorName isn't nil, so colorNameToUse
is set to "green"
Range Operators
Swift includes several range operators, which are shortcuts for
expressing a range of values.
Half-open ranges are particularly useful when you work with zero-
based lists such as arrays, where it’s useful to count up to (but not
including) the length of the list:
Note that the array contains four items, but 0..<count only counts as
far as 3 (the index of the last item in the array), because it’s a half-
open range. For more about arrays, see Arrays.
One-Sided Ranges
The closed range operator has an alternative form for ranges that
continue as far as possible in one direction—for example, a range
that includes all the elements of an array from index 2 to the end of
the array. In these cases, you can omit the value from one side of the
range operator. This kind of range is called a one-sided range
because the operator has a value on only one side. For example:
The half-open range operator also has a one-sided form that’s written
with only its final value. Just like when you include a value on both
sides, the final value isn’t part of the range. For example:
Logical Operators
Logical operators modify or combine the Boolean logic values true
and false. Swift supports the three standard logical operators found
in C-based languages:
Logical OR (a || b)
This example considers two Bool values and only allows access if
both values are true:
Logical OR Operator
The logical OR operator (a || b) is an infix operator made from two
adjacent pipe characters. You use it to create logical expressions in
which only one of the two values has to be true for the overall
expression to be true.
Like the Logical AND operator above, the Logical OR operator uses
short-circuit evaluation to consider its expressions. If the left side of a
Logical OR expression is true, the right side isn’t evaluated, because
it can’t change the outcome of the overall expression.
In the example below, the first Bool value (hasDoorKey) is false, but
the second value (knowsOverridePassword) is true. Because one
value is true, the overall expression also evaluates to true, and
access is allowed:
If we’ve entered the correct door code and passed the retina scan, or
if we have a valid door key, or if we know the emergency override
NOTE
The Swift logical operators && and || are left-associative, meaning that
compound expressions with multiple logical operators evaluate the leftmost
subexpression first.
Explicit Parentheses
It’s sometimes useful to include parentheses when they’re not strictly
needed, to make the intention of a complex expression easier to
read. In the door access example above, it’s useful to add
parentheses around the first part of the compound expression to
make its intent explicit:
The parentheses make it clear that the first two values are
considered as part of a separate possible state in the overall logic.
The output of the compound expression doesn’t change, but the
overall intention is clearer to the reader. Readability is always
NOTE
String Literals
Note that Swift infers a type of String for the someString constant
because it’s initialized with a string literal value.
A multiline string literal includes all of the lines between its opening
and closing quotation marks. The string begins on the first line after
the opening quotation marks (""") and ends on the line before the
To make a multiline string literal that begins or ends with a line feed,
write a blank line as the first or last line. For example:
In the example above, even though the entire multiline string literal is
indented, the first and last lines in the string don’t begin with any
whitespace. The middle line has more indentation than the closing
quotation marks, so it starts with that extra four-space indentation.
The code below shows four examples of these special characters. The
wiseWords constant contains two escaped double quotation marks.
The dollarSign, blackHeart, and sparklingHeart constants
demonstrate the Unicode scalar format:
1 if emptyString.isEmpty {
2 print("Nothing to see here")
3 }
4 // Prints "Nothing to see here"
String Mutability
You indicate whether a particular String can be modified (or mutated)
by assigning it to a variable (in which case it can be modified), or to a
constant (in which case it can’t be modified):
NOTE
NOTE
String Interpolation
String interpolation is a way to construct a new String value from a
mix of constants, variables, literals, and expressions by including their
values inside a string literal. You can use string interpolation in both
single-line and multiline string literals. Each item that you insert into
the string literal is wrapped in a pair of parentheses, prefixed by a
backslash (\):
1 let multiplier = 3
2 let message = "\(multiplier) times 2.5 is \
(Double(multiplier) * 2.5)"
3 // message is "3 times 2.5 is 7.5"
NOTE
Unicode
Unicode is an international standard for encoding, representing, and
processing text in different writing systems. It enables you to represent
almost any character from any language in a standardized form, and
to read and write those characters to and from an external source
such as a text file or web page. Swift’s String and Character types
are fully Unicode-compliant, as described in this section.
Counting Characters
To retrieve a count of the Character values in a string, use the count
property of the string:
For example, if you initialize a new string with the four-character word
cafe, and then append a COMBINING ACUTE ACCENT (U+0301) to the end
of the string, the resulting string will still have a character count of 4,
with a fourth character of é, not e:
NOTE
String Indices
Each String value has an associated index type, String.Index, which
corresponds to the position of each Character in the string.
You access the indices before and after a given index using the
index(before:) and index(after:) methods of String. To access an
index farther away from the given index, you can use the
index(_:offsetBy:) method instead of calling one of these methods
multiple times.
1 greeting[greeting.endIndex] // Error
2 greeting.index(after: greeting.endIndex) // Error
You can use the startIndex and endIndex properties and the
index(before:), index(after:), and index(_:offsetBy:) methods on any
type that conforms to the Collection protocol. This includes String, as
shown here, as well as collection types such as Array, Dictionary, and Set.
NOTE
Substrings
When you get a substring from a string—for example, using a
subscript or a method like prefix(_:)—the result is an instance of
Substring, not another string. Substrings in Swift have most of the
same methods as strings, which means you can work with substrings
the same way you work with strings. However, unlike strings, you use
substrings for only a short amount of time while performing actions on
a string. When you’re ready to store the result for a longer time, you
convert the substring to an instance of String. For example:
Comparing Strings
Swift provides three ways to compare textual values: string and
character equality, prefix equality, and suffix equality.
Two String values (or two Character values) are considered equal if
their extended grapheme clusters are canonically equivalent.
Extended grapheme clusters are canonically equivalent if they have
the same linguistic meaning and appearance, even if they’re
composed from different Unicode scalars behind the scenes.
1 let romeoAndJuliet = [
2 "Act 1 Scene 1: Verona, A public place",
3 "Act 1 Scene 2: Capulet's mansion",
4 "Act 1 Scene 3: A room in Capulet's mansion",
5 "Act 1 Scene 4: A street outside Capulet's
mansion",
6 "Act 1 Scene 5: The Great Hall in Capulet's
mansion",
7 "Act 2 Scene 1: Outside Capulet's mansion",
8 "Act 2 Scene 2: Capulet's orchard",
9 "Act 2 Scene 3: Outside Friar Lawrence's cell",
10 "Act 2 Scene 4: A street in Verona",
11 "Act 2 Scene 5: Capulet's mansion",
12 "Act 2 Scene 6: Friar Lawrence's cell"
13 ]
1 var act1SceneCount = 0
2 for scene in romeoAndJuliet {
3 if scene.hasPrefix("Act 1 ") {
4 act1SceneCount += 1
5 }
6 }
7 print("There are \(act1SceneCount) scenes in Act 1")
8 // Prints "There are 5 scenes in Act 1"
NOTE
UTF-8 Representation
You can access a UTF-8 representation of a String by iterating over
its utf8 property. This property is of type String.UTF8View, which is a
collection of unsigned 8-bit (UInt8) values, one for each byte in the
string’s UTF-8 representation:
In the example above, the first three decimal codeUnit values (68, 111,
103) represent the characters D, o, and g, whose UTF-8 representation
is the same as their ASCII representation. The next three decimal
codeUnit values (226, 128, 188) are a three-byte UTF-8 representation
of the DOUBLE EXCLAMATION MARK character. The last four codeUnit
values (240, 159, 144, 182) are a four-byte UTF-8 representation of the
DOG FACE character.
UTF-16 Representation
You can access a UTF-16 representation of a String by iterating over
its utf16 property. This property is of type String.UTF16View, which is
a collection of unsigned 16-bit (UInt16) values, one for each 16-bit
code unit in the string’s UTF-16 representation:
Again, the first three codeUnit values (68, 111, 103) represent the
characters D, o, and g, whose UTF-16 code units have the same
values as in the string’s UTF-8 representation (because these
Unicode scalars represent ASCII characters).
The fifth and sixth codeUnit values (55357 and 56374) are a UTF-16
surrogate pair representation of the DOG FACE character. These values
are a high-surrogate value of U+D83D (decimal value 55357) and a low-
surrogate value of U+DC36 (decimal value 56374).
Each UnicodeScalar has a value property that returns the scalar’s 21-
bit value, represented within a UInt32 value:
The value properties for the first three UnicodeScalar values (68, 111,
103) once again represent the characters D, o, and g.
Arrays, sets, and dictionaries in Swift are always clear about the types
of values and keys that they can store. This means that you can’t
insert a value of the wrong type into a collection by mistake. It also
means you can be confident about the type of values you will retrieve
from a collection.
NOTE
Swift’s array, set, and dictionary types are implemented as generic collections.
For more about generic types and collections, see Generics.
Mutability of Collections
If you create an array, a set, or a dictionary, and assign it to a variable,
the collection that’s created will be mutable. This means that you can
change (or mutate) the collection after it’s created by adding,
NOTE
It’s good practice to create immutable collections in all cases where the
collection doesn’t need to change. Doing so makes it easier for you to reason
about your code and enables the Swift compiler to optimize the performance of
the collections you create.
Arrays
An array stores values of the same type in an ordered list. The same
value can appear in an array multiple times at different positions.
NOTE
Note that the type of the someInts variable is inferred to be [Int] from
the type of the initializer.
1 someInts.append(3)
2 // someInts now contains 1 value of type Int
3 someInts = []
4 // someInts is now an empty array, but is still of
type [Int]
NOTE
In this case, the array literal contains two String values and nothing
else. This matches the type of the shoppingList variable’s declaration
(an array that can only contain String values), and so the assignment
of the array literal is permitted as a way to initialize shoppingList with
two initial items.
Thanks to Swift’s type inference, you don’t have to write the type of
the array if you’re initializing it with an array literal containing values of
the same type. The initialization of shoppingList could have been
written in a shorter form instead:
Because all values in the array literal are of the same type, Swift can
infer that [String] is the correct type to use for the shoppingList
variable.
To find out the number of items in an array, check its read-only count
property:
1 if shoppingList.isEmpty {
2 print("The shopping list is empty.")
3 } else {
4 print("The shopping list isn't empty.")
5 }
6 // Prints "The shopping list isn't empty."
You can add a new item to the end of an array by calling the array’s
append(_:) method:
1 shoppingList.append("Flour")
2 // shoppingList now contains 3 items, and someone is
making pancakes
Retrieve a value from the array by using subscript syntax, passing the
index of the value you want to retrieve within square brackets
immediately after the name of the array:
NOTE
The first item in the array has an index of 0, not 1. Arrays in Swift are always
zero-indexed.
When you use subscript syntax, the index you specify needs to be
valid. For example, writing shoppingList[shoppingList.count] =
"Salt" to try to append an item to the end of the array results in a
runtime error.
To insert an item into the array at a specified index, call the array’s
insert(_:at:) method:
This call to the insert(_:at:) method inserts a new item with a value
of "Maple Syrup" at the very beginning of the shopping list, indicated
by an index of 0.
Similarly, you remove an item from the array with the remove(at:)
method. This method removes the item at the specified index and
returns the removed item (although you can ignore the returned value
if you don’t need it):
If you try to access or modify a value for an index that’s outside of an array’s
existing bounds, you will trigger a runtime error. You can check that an index is
valid before using it by comparing it to the array’s count property. The largest
valid index in an array is count - 1 because arrays are indexed from zero—
however, when count is 0 (meaning the array is empty), there are no valid
indexes.
Any gaps in an array are closed when an item is removed, and so the
value at index 0 is once again equal to "Six eggs":
1 firstItem = shoppingList[0]
2 // firstItem is now equal to "Six eggs"
If you want to remove the final item from an array, use the
removeLast() method rather than the remove(at:) method to avoid
the need to query the array’s count property. Like the remove(at:)
method, removeLast() returns the removed item:
If you need the integer index of each item as well as its value, use the
enumerated() method to iterate over the array instead. For each item
in the array, the enumerated() method returns a tuple composed of an
integer and the item. The integers start at zero and count up by one for
each item; if you enumerate over a whole array, these integers match
the items’ indices. You can decompose the tuple into temporary
constants or variables as part of the iteration:
NOTE
All of Swift’s basic types (such as String, Int, Double, and Bool) are
hashable by default, and can be used as set value types or dictionary
key types. Enumeration case values without associated values (as
described in Enumerations) are also hashable by default.
NOTE
You can use your own custom types as set value types or dictionary key types
by making them conform to the Hashable protocol from the Swift standard
library. For information about implementing the required hash(into:) method,
see Hashable. For information about conforming to protocols, see Protocols.
NOTE
1 letters.insert("a")
2 // letters now contains 1 value of type Character
3 letters = []
4 // letters is now an empty set, but is still of type
Set<Character>
NOTE
A set type can’t be inferred from an array literal alone, so the type Set
must be explicitly declared. However, because of Swift’s type
inference, you don’t have to write the type of the set’s elements if
you’re initializing it with an array literal that contains values of just one
type. The initialization of favoriteGenres could have been written in a
shorter form instead:
To find out the number of items in a set, check its read-only count
property:
1 if favoriteGenres.isEmpty {
2 print("As far as music goes, I'm not picky.")
3 } else {
4 print("I have particular music preferences.")
5 }
6 // Prints "I have particular music preferences."
You can add a new item into a set by calling the set’s insert(_:)
method:
1 favoriteGenres.insert("Jazz")
2 // favoriteGenres now contains 4 items
1 if favoriteGenres.contains("Funk") {
2 print("I get up on the good foot.")
3 } else {
4 print("It's too funky in here.")
5 }
6 // Prints "It's too funky in here."
Swift’s Set type doesn’t have a defined ordering. To iterate over the
values of a set in a specific order, use the sorted() method, which
returns the set’s elements as an array sorted using the < operator.
Use the union(_:) method to create a new set with all of the
values in both sets.
Dictionaries
A dictionary stores associations between keys of the same type and
values of the same type in a collection with no defined ordering. Each
value is associated with a unique key, which acts as an identifier for
that value within the dictionary. Unlike items in an array, items in a
dictionary don’t have a specified order. You use a dictionary when you
need to look up values based on their identifier, in much the same way
that a real-world dictionary is used to look up the definition for a
particular word.
NOTE
NOTE
A dictionary Key type must conform to the Hashable protocol, like a set’s value
type.
You can also write the type of a dictionary in shorthand form as [Key:
Value]. Although the two forms are functionally identical, the
shorthand form is preferred and is used throughout this guide when
referring to the type of a dictionary.
This dictionary literal contains two String: String pairs. This key-
value type matches the type of the airports variable declaration (a
dictionary with only String keys, and only String values), and so the
assignment of the dictionary literal is permitted as a way to initialize
the airports dictionary with two initial items.
As with arrays, you don’t have to write the type of the dictionary if
you’re initializing it with a dictionary literal whose keys and values
have consistent types. The initialization of airports could have been
written in a shorter form instead:
Because all keys in the literal are of the same type as each other, and
likewise all values are of the same type as each other, Swift can infer
that [String: String] is the correct type to use for the airports
dictionary.
1 if airports.isEmpty {
2 print("The airports dictionary is empty.")
3 } else {
4 print("The airports dictionary isn't empty.")
5 }
6 // Prints "The airports dictionary isn't empty."
You can add a new item to a dictionary with subscript syntax. Use a
new key of the appropriate type as the subscript index, and assign a
new value of the appropriate type:
1 airports["LHR"] = "London"
2 // the airports dictionary now contains 3 items
You can also use subscript syntax to change the value associated with
a particular key:
You can also use subscript syntax to retrieve a value from the
dictionary for a particular key. Because it’s possible to request a key
for which no value exists, a dictionary’s subscript returns an optional
value of the dictionary’s value type. If the dictionary contains a value
for the requested key, the subscript returns an optional value
containing the existing value for that key. Otherwise, the subscript
returns nil:
If you need to use a dictionary’s keys or values with an API that takes
an Array instance, initialize a new array with the keys or values
property:
Swift provides a variety of control flow statements. These include while loops to
perform a task multiple times; if, guard, and switch statements to execute
different branches of code based on certain conditions; and statements such as
break and continue to transfer the flow of execution to another point in your
code.
Swift also provides a for-in loop that makes it easy to iterate over arrays,
dictionaries, ranges, strings, and other sequences.
For-In Loops
You use the for-in loop to iterate over a sequence, such as items in an array,
ranges of numbers, or characters in a string.
This example uses a for-in loop to iterate over the items in an array:
The contents of a Dictionary are inherently unordered, and iterating over them
doesn’t guarantee the order in which they will be retrieved. In particular, the
order you insert items into a Dictionary doesn’t define the order they’re
iterated. For more about arrays and dictionaries, see Collection Types.
You can also use for-in loops with numeric ranges. This example prints the first
few entries in a five-times table:
If you don’t need each value from a sequence, you can ignore the values by
using an underscore in place of a variable name.
1 let base = 3
2 let power = 10
3 var answer = 1
4 for _ in 1...power {
5 answer *= base
6 }
7 print("\(base) to the power of \(power) is \(answer)")
8 // Prints "3 to the power of 10 is 59049"
The example above calculates the value of one number to the power of another
(in this case, 3 to the power of 10). It multiplies a starting value of 1 (that is, 3 to
the power of 0) by 3, ten times, using a closed range that starts with 1 and ends
with 10. For this calculation, the individual counter values each time through the
loop are unnecessary—the code simply executes the loop the correct number of
times. The underscore character (_) used in place of a loop variable causes the
individual values to be ignored and doesn’t provide access to the current value
during each iteration of the loop.
In some situations, you might not want to use closed ranges, which include both
endpoints. Consider drawing the tick marks for every minute on a watch face.
You want to draw 60 tick marks, starting with the 0 minute. Use the half-open
range operator (..<) to include the lower bound but not the upper bound. For
more about ranges, see Range Operators.
Some users might want fewer tick marks in their UI. They could prefer one mark
every 5 minutes instead. Use the stride(from:to:by:) function to skip the
unwanted marks.
1 let minuteInterval = 5
2 for tickMark in stride(from: 0, to: minutes, by:
minuteInterval) {
3 // render the tick mark every 5 minutes (0, 5, 10, 15 ...
45, 50, 55)
4 }
1 let hours = 12
2 let hourInterval = 3
3 for tickMark in stride(from: 3, through: hours, by:
hourInterval) {
4 // render the tick mark every 3 hours (3, 6, 9, 12)
5 }
The examples above use a for-in loop to iterate ranges, arrays, dictionaries,
and strings. However, you can use this syntax to iterate any collection, including
your own classes and collection types, as long as those types conform to the
Sequence protocol.
While Loops
while evaluates its condition at the start of each pass through the loop.
repeat-while evaluates its condition at the end of each pass through the
loop.
While
A while loop starts by evaluating a single condition. If the condition is true, a set
of statements is repeated until the condition becomes false.
while condition {
statements
}
This example plays a simple game of Snakes and Ladders (also known as
Chutes and Ladders):
The board has 25 squares, and the aim is to land on or beyond square 25.
The player’s starting square is “square zero”, which is just off the bottom-
left corner of the board.
If your turn ends at the bottom of a ladder, you move up that ladder.
If your turn ends at the head of a snake, you move down that snake.
The game board is represented by an array of Int values. Its size is based on a
constant called finalSquare, which is used to initialize the array and also to
check for a win condition later in the example. Because the players start off the
board, on “square zero”, the board is initialized with 26 zero Int values, not 25.
1 let finalSquare = 25
2 var board = [Int](repeating: 0, count: finalSquare + 1)
Some squares are then set to have more specific values for the snakes and
ladders. Squares with a ladder base have a positive number to move you up the
board, whereas squares with a snake head have a negative number to move
you back down the board.
Square 3 contains the bottom of a ladder that moves you up to square 11. To
represent this, board[03] is equal to +08, which is equivalent to an integer value
of 8 (the difference between 3 and 11). To align the values and statements, the
unary plus operator (+i) is explicitly used with the unary minus operator (-i) and
numbers lower than 10 are padded with zeros. (Neither stylistic technique is
strictly necessary, but they lead to neater code.)
The example above uses a very simple approach to dice rolling. Instead of
generating a random number, it starts with a diceRoll value of 0. Each time
through the while loop, diceRoll is incremented by one and is then checked to
see whether it has become too large. Whenever this return value equals 7, the
dice roll has become too large and is reset to a value of 1. The result is a
sequence of diceRoll values that’s always 1, 2, 3, 4, 5, 6, 1, 2 and so on.
After rolling the dice, the player moves forward by diceRoll squares. It’s
possible that the dice roll may have moved the player beyond square 25, in
which case the game is over. To cope with this scenario, the code checks that
square is less than the board array’s count property. If square is valid, the value
stored in board[square] is added to the current square value to move the player
up or down any ladders or snakes.
NOTE
If this check isn’t performed, board[square] might try to access a value outside the
bounds of the board array, which would trigger a runtime error.
A while loop is appropriate in this case, because the length of the game isn’t
clear at the start of the while loop. Instead, the loop is executed until a particular
condition is satisfied.
Repeat-While
The other variation of the while loop, known as the repeat-while loop, performs
a single pass through the loop block first, before considering the loop’s
condition. It then continues to repeat the loop until the condition is false.
NOTE
repeat {
statements
} while condition
Here’s the Snakes and Ladders example again, written as a repeat-while loop
rather than a while loop. The values of finalSquare, board, square, and
diceRoll are initialized in exactly the same way as with a while loop.
1 let finalSquare = 25
2 var board = [Int](repeating: 0, count: finalSquare + 1)
3 board[03] = +08; board[06] = +11; board[09] = +09; board[10]
= +02
4 board[14] = -10; board[19] = -11; board[22] = -02; board[24]
= -08
5 var square = 0
6 var diceRoll = 0
At the start of the game, the player is on “square zero”. board[0] always equals
0 and has no effect.
1 repeat {
2 // move up or down for a snake or ladder
3 square += board[square]
4 // roll the dice
5 diceRoll += 1
6 if diceRoll == 7 { diceRoll = 1 }
7 // move by the rolled amount
8 square += diceRoll
9 } while square < finalSquare
10 print("Game over!")
After the code checks for snakes and ladders, the dice is rolled and the player is
moved forward by diceRoll squares. The current loop execution then ends.
The loop’s condition (while square < finalSquare) is the same as before, but
this time it’s not evaluated until the end of the first run through the loop. The
structure of the repeat-while loop is better suited to this game than the while
loop in the previous example. In the repeat-while loop above, square +=
board[square] is always executed immediately after the loop’s while condition
confirms that square is still on the board. This behavior removes the need for the
array bounds check seen in the while loop version of the game described
earlier.
Conditional Statements
Swift provides two ways to add conditional branches to your code: the if
statement and the switch statement. Typically, you use the if statement to
evaluate simple conditions with only a few possible outcomes. The switch
statement is better suited to more complex conditions with multiple possible
permutations and is useful in situations where pattern matching can help select
an appropriate code branch to execute.
If
In its simplest form, the if statement has a single if condition. It executes a set
of statements only if that condition is true.
1 var temperatureInFahrenheit = 30
2 if temperatureInFahrenheit <= 32 {
3 print("It's very cold. Consider wearing a scarf.")
4 }
5 // Prints "It's very cold. Consider wearing a scarf."
The example above checks whether the temperature is less than or equal to 32
degrees Fahrenheit (the freezing point of water). If it is, a message is printed.
Otherwise, no message is printed, and code execution continues after the if
statement’s closing brace.
One of these two branches is always executed. Because the temperature has
increased to 40 degrees Fahrenheit, it’s no longer cold enough to advise
wearing a scarf and so the else branch is triggered instead.
1 temperatureInFahrenheit = 90
2 if temperatureInFahrenheit <= 32 {
3 print("It's very cold. Consider wearing a scarf.")
4 } else if temperatureInFahrenheit >= 86 {
5 print("It's really warm. Don't forget to wear
sunscreen.")
6 } else {
7 print("It's not that cold. Wear a t-shirt.")
8 }
9 // Prints "It's really warm. Don't forget to wear sunscreen."
The final else clause is optional, however, and can be excluded if the set of
conditions doesn’t need to be complete.
Because the temperature is neither too cold nor too warm to trigger the if or
else if conditions, no message is printed.
Switch
A switch statement considers a value and compares it against several possible
matching patterns. It then executes an appropriate block of code, based on the
first pattern that matches successfully. A switch statement provides an
alternative to the if statement for responding to multiple potential states.
In its simplest form, a switch statement compares a value against one or more
values of the same type.
Every switch statement must be exhaustive. That is, every possible value of the
type being considered must be matched by one of the switch cases. If it’s not
appropriate to provide a case for every possible value, you can define a default
case to cover any values that aren’t addressed explicitly. This default case is
indicated by the default keyword, and must always appear last.
The switch statement’s first case matches the first letter of the English alphabet,
a, and its second case matches the last letter, z. Because the switch must have
a case for every possible character, not just every alphabetic character, this
switch statement uses a default case to match all characters other than a and
z. This provision ensures that the switch statement is exhaustive.
No Implicit Fallthrough
NOTE
Although break isn’t required in Swift, you can use a break statement to match and ignore
a particular case or to break out of a matched case before that case has completed its
execution. For details, see Break in a Switch Statement.
The body of each case must contain at least one executable statement. It isn’t
valid to write the following code, because the first case is empty:
Unlike a switch statement in C, this switch statement doesn’t match both "a"
and "A". Rather, it reports a compile-time error that case "a": doesn’t contain
any executable statements. This approach avoids accidental fallthrough from
one case to another and makes for safer code that’s clearer in its intent.
To make a switch with a single case that matches both "a" and "A", combine
the two values into a compound case, separating the values with commas.
For readability, a compound case can also be written over multiple lines. For
more information about compound cases, see Compound Cases.
NOTE
To explicitly fall through at the end of a particular switch case, use the fallthrough
keyword, as described in Fallthrough.
Interval Matching
Values in switch cases can be checked for their inclusion in an interval. This
example uses number intervals to provide a natural-language count for
numbers of any size:
Tuples
You can use tuples to test multiple values in the same switch statement. Each
element of the tuple can be tested against a different value or interval of values.
Alternatively, use the underscore character (_), also known as the wildcard
pattern, to match any possible value.
The example below takes an (x, y) point, expressed as a simple tuple of type
(Int, Int), and categorizes it on the graph that follows the example.
Unlike C, Swift allows multiple switch cases to consider the same value or
values. In fact, the point (0, 0) could match all four of the cases in this example.
However, if multiple matches are possible, the first matching case is always
used. The point (0, 0) would match case (0, 0) first, and so all other matching
cases would be ignored.
Value Bindings
A switch case can name the value or values it matches to temporary constants
or variables, for use in the body of the case. This behavior is known as value
binding, because the values are bound to temporary constants or variables
within the case’s body.
The example below takes an (x, y) point, expressed as a tuple of type (Int,
Int), and categorizes it on the graph that follows:
The switch statement determines whether the point is on the red x-axis, on the
green y-axis, or elsewhere (on neither axis).
After the temporary constants are declared, they can be used within the case’s
code block. Here, they’re used to print the categorization of the point.
This switch statement doesn’t have a default case. The final case, case let
(x, y), declares a tuple of two placeholder constants that can match any value.
Because anotherPoint is always a tuple of two values, this case matches all
possible remaining values, and a default case isn’t needed to make the switch
statement exhaustive.
Where
A switch case can use a where clause to check for additional conditions.
As in the previous example, the final case matches all possible remaining
values, and so a default case isn’t needed to make the switch statement
exhaustive.
Compound Cases
Multiple switch cases that share the same body can be combined by writing
several patterns after case, with a comma between each of the patterns. If any
of the patterns match, then the case is considered to match. The patterns can
be written over multiple lines if the list is long. For example:
The switch statement’s first case matches all five lowercase vowels in the
English language. Similarly, its second case matches all lowercase English
consonants. Finally, the default case matches any other character.
Compound cases can also include value bindings. All of the patterns of a
compound case have to include the same set of value bindings, and each
binding has to get a value of the same type from all of the patterns in the
compound case. This ensures that, no matter which part of the compound case
matched, the code in the body of the case can always access a value for the
bindings and that the value always has the same type.
The case above has two patterns: (let distance, 0) matches points on the x-
axis and (0, let distance) matches points on the y-axis. Both patterns include
continue
break
fallthrough
return
throw
The continue, break, and fallthrough statements are described below. The
return statement is described in Functions, and the throw statement is
described in Propagating Errors Using Throwing Functions.
Continue
The continue statement tells a loop to stop what it’s doing and start again at the
beginning of the next iteration through the loop. It says “I am done with the
current loop iteration” without leaving the loop altogether.
The following example removes all vowels and spaces from a lowercase string
to create a cryptic puzzle phrase:
The code above calls the continue keyword whenever it matches a vowel or a
space, causing the current iteration of the loop to end immediately and to jump
straight to the start of the next iteration.
Break
The break statement ends execution of an entire control flow statement
immediately. The break statement can be used inside a switch or loop
statement when you want to terminate the execution of the switch or loop
statement earlier than would otherwise be the case.
When used inside a loop statement, break ends the loop’s execution
immediately and transfers control to the code after the loop’s closing brace (}).
No further code from the current iteration of the loop is executed, and no further
iterations of the loop are started.
When used inside a switch statement, break causes the switch statement to
end its execution immediately and to transfer control to the code after the
This behavior can be used to match and ignore one or more cases in a switch
statement. Because Swift’s switch statement is exhaustive and doesn’t allow
empty cases, it’s sometimes necessary to deliberately match and ignore a case
in order to make your intentions explicit. You do this by writing the break
statement as the entire body of the case you want to ignore. When that case is
matched by the switch statement, the break statement inside the case ends the
switch statement’s execution immediately.
NOTE
After the switch statement completes its execution, the example uses optional
binding to determine whether a value was found. The possibleIntegerValue
variable has an implicit initial value of nil by virtue of being an optional type,
Because it’s not practical to list every possible Character value in the example
above, a default case handles any characters that aren’t matched. This
default case doesn’t need to perform any action, and so it’s written with a
single break statement as its body. As soon as the default case is matched, the
break statement ends the switch statement’s execution, and code execution
continues from the if let statement.
Fallthrough
In Swift, switch statements don’t fall through the bottom of each case and into
the next one. That is, the entire switch statement completes its execution as
soon as the first matching case is completed. By contrast, C requires you to
insert an explicit break statement at the end of every switch case to prevent
fallthrough. Avoiding default fallthrough means that Swift switch statements are
much more concise and predictable than their counterparts in C, and thus they
avoid executing multiple switch cases by mistake.
If you need C-style fallthrough behavior, you can opt in to this behavior on a
case-by-case basis with the fallthrough keyword. The example below uses
fallthrough to create a textual description of a number.
1 let integerToDescribe = 5
2 var description = "The number \(integerToDescribe) is"
3 switch integerToDescribe {
4 case 2, 3, 5, 7, 11, 13, 17, 19:
5 description += " a prime number, and also"
6 fallthrough
7 default:
8 description += " an integer."
9 }
10 print(description)
11 // Prints "The number 5 is a prime number, and also an
integer."
After the switch statement has finished executing, the number’s description is
printed using the print(_:separator:terminator:) function. In this example,
the number 5 is correctly identified as a prime number.
NOTE
The fallthrough keyword doesn’t check the case conditions for the switch case that it
causes execution to fall into. The fallthrough keyword simply causes code execution to
move directly to the statements inside the next case (or default case) block, as in C’s
standard switch statement behavior.
Labeled Statements
In Swift, you can nest loops and conditional statements inside other loops and
conditional statements to create complex control flow structures. However,
loops and conditional statements can both use the break statement to end their
execution prematurely. Therefore, it’s sometimes useful to be explicit about
which loop or conditional statement you want a break statement to terminate.
Similarly, if you have multiple nested loops, it can be useful to be explicit about
which loop the continue statement should affect.
To achieve these aims, you can mark a loop statement or conditional statement
with a statement label. With a conditional statement, you can use a statement
label with the break statement to end the execution of the labeled statement.
With a loop statement, you can use a statement label with the break or continue
statement to end or continue the execution of the labeled statement.
The following example uses the break and continue statements with a labeled
while loop for an adapted version of the Snakes and Ladders game that you
saw earlier in this chapter. This time around, the game has an extra rule:
If a particular dice roll would take you beyond square 25, you must roll again
until you roll the exact number needed to land on square 25.
The values of finalSquare, board, square, and diceRoll are initialized in the
same way as before:
This version of the game uses a while loop and a switch statement to
implement the game’s logic. The while loop has a statement label called
gameLoop to indicate that it’s the main game loop for the Snakes and Ladders
game.
The while loop’s condition is while square != finalSquare, to reflect that you
must land exactly on square 25.
The dice is rolled at the start of each loop. Rather than moving the player
immediately, the loop uses a switch statement to consider the result of the
move and to determine whether the move is allowed:
If the dice roll will move the player onto the final square, the game is over.
The break gameLoop statement transfers control to the first line of code
outside of the while loop, which ends the game.
If the dice roll will move the player beyond the final square, the move is
invalid and the player needs to roll again. The continue gameLoop
statement ends the current while loop iteration and begins the next
iteration of the loop.
NOTE
If the break statement above didn’t use the gameLoop label, it would break out of the
switch statement, not the while statement. Using the gameLoop label makes it clear which
control statement should be terminated.
It isn’t strictly necessary to use the gameLoop label when calling continue gameLoop to
jump to the next iteration of the loop. there’s only one loop in the game, and therefore no
ambiguity as to which loop the continue statement will affect. However, there’s no harm in
using the gameLoop label with the continue statement. Doing so is consistent with the
label’s use alongside the break statement and helps make the game’s logic clearer to read
and understand.
Early Exit
A guard statement, like an if statement, executes statements depending on the
Boolean value of an expression. You use a guard statement to require that a
condition must be true in order for the code after the guard statement to be
executed. Unlike an if statement, a guard statement always has an else clause
—the code inside the else clause is executed if the condition isn’t true.
If the guard statement’s condition is met, code execution continues after the
guard statement’s closing brace. Any variables or constants that were assigned
values using an optional binding as part of the condition are available for the
rest of the code block that the guard statement appears in.
If that condition isn’t met, the code inside the else branch is executed. That
branch must transfer control to exit the code block in which the guard statement
appears. It can do this with a control transfer statement such as return, break,
continue, or throw, or it can call a function or method that doesn’t return, such
as fatalError(_:file:line:).
The compiler uses availability information in the SDK to verify that all of the APIs
used in your code are available on the deployment target specified by your
project. Swift reports an error at compile time if you try to use an API that isn’t
available.
The availability condition above specifies that in iOS, the body of the if
statement executes only in iOS 10 and later; in macOS, only in macOS 10.12
and later. The last argument, *, is required and specifies that on any other
platform, the body of the if executes on the minimum deployment target
specified by your target.
In its general form, the availability condition takes a list of platform names and
versions. You use platform names such as iOS, macOS, watchOS, and tvOS—for
the full list, see Declaration Attributes. In addition to specifying major version
When you use an availability condition with a guard statement, it refines the
availability information that’s used for the rest of the code in that code block.
1 @available(macOS 10.12, *)
2 struct ColorPreference {
3 var bestColor = "blue"
4 }
5
6 func chooseBestColor() -> String {
7 guard #available(macOS 10.12, *) else {
8 return "gray"
9 }
10 let colors = ColorPreference()
11 return colors.bestColor
12 }
1 if #available(iOS 10, *) {
2 } else {
3 // Fallback code
4 }
5
6 if #unavailable(iOS 10) {
7 // Fallback code
8 }
Using the #unavailable form helps make your code more readable when the
check contains only fallback code.
Every function has a function name, which describes the task that the
function performs. To use a function, you “call” that function with its
name and pass it input values (known as arguments) that match the
1 print(greet(person: "Anna"))
2 // Prints "Hello, Anna!"
3 print(greet(person: "Brian"))
4 // Prints "Hello, Brian!"
NOTE
You can call the greet(person:) function multiple times with different
input values. The example above shows what happens if it’s called
with an input value of "Anna", and an input value of "Brian". The
function returns a tailored greeting in each case.
To make the body of this function shorter, you can combine the
message creation and the return statement into one line:
This function takes a person’s name and whether they have already
been greeted as input, and returns an appropriate greeting for that
person:
NOTE
Strictly speaking, this version of the greet(person:) function does still return
a value, even though no return value is defined. Functions without a defined
return type return a special value of type Void. This is simply an empty tuple,
which is written as ().
NOTE
Return values can be ignored, but a function that says it will return a value
must always do so. A function with a defined return type can’t allow control to
fall out of the bottom of the function without returning a value, and attempting
to do so will result in a compile-time error.
Note that the tuple’s members don’t need to be named at the point
that the tuple is returned from the function, because their names are
already specified as part of the function’s return type.
NOTE
An optional tuple type such as (Int, Int)? is different from a tuple that
contains optional types such as (Int?, Int?). With an optional tuple type,
the entire tuple is optional, not just each individual value within the tuple.
You can use optional binding to check whether this version of the
minMax(array:) function returns an actual tuple value or nil:
NOTE
The code you write as an implicit return value needs to return some value. For
example, you can’t use print(13) as an implicit return value. However, you
can use a function that never returns like fatalError("Oh no!") as an
implicit return value, because Swift knows that the implicit return doesn’t
happen.
All parameters must have unique names. Although it’s possible for
multiple parameters to have the same argument label, unique
argument labels help make your code more readable.
Variadic Parameters
A variadic parameter accepts zero or more values of a specified type.
You use a variadic parameter to specify that the parameter can be
passed a varying number of input values when the function is called.
Write variadic parameters by inserting three period characters (...)
after the parameter’s type name.
In-Out Parameters
NOTE
In-out parameters can’t have default values, and variadic parameters can’t be
marked as inout.
1 var someInt = 3
2 var anotherInt = 107
3 swapTwoInts(&someInt, &anotherInt)
4 print("someInt is now \(someInt), and anotherInt is
now \(anotherInt)")
5 // Prints "someInt is now 107, and anotherInt is now
3"
The example above shows that the original values of someInt and
anotherInt are modified by the swapTwoInts(_:_:) function, even
though they were originally defined outside of the function.
In-out parameters aren’t the same as returning a value from a function. The
swapTwoInts example above doesn’t define a return type or return a value,
but it still modifies the values of someInt and anotherInt. In-out parameters
are an alternative way for a function to have an effect outside of the scope of
its function body.
Function Types
Every function has a specific function type, made up of the parameter
types and the return type of the function.
For example:
The type of both of these functions is (Int, Int) -> Int. This can
be read as:
“A function that has two parameters, both of type Int, and that returns
a value of type Int.”
1 func printHelloWorld() {
2 print("hello, world")
3 }
You can now call the assigned function with the name mathFunction:
1 mathFunction = multiplyTwoInts
2 print("Result: \(mathFunction(2, 3))")
3 // Prints "Result: 6"
As with any other type, you can leave it to Swift to infer the function
type when you assign a function to a constant or variable:
1 var currentValue = 3
2 let moveNearerToZero = chooseStepFunction(backward:
currentValue > 0)
3 // moveNearerToZero now refers to the stepBackward()
function
1 print("Counting to zero:")
2 // Counting to zero:
3 while currentValue != 0 {
4 print("\(currentValue)... ")
5 currentValue = moveNearerToZero(currentValue)
6 }
7 print("zero!")
8 // 3...
9 // 2...
10 // 1...
11 // zero!
Nested Functions
All of the functions you have encountered so far in this chapter have
been examples of global functions, which are defined at a global
scope. You can also define functions inside the bodies of other
functions, known as nested functions.
NOTE
Don’t worry if you aren’t familiar with the concept of capturing. It’s explained in
detail below in Capturing Values.
Nested functions are closures that have a name and can capture
values from their enclosing function.
Closure Expressions
Nested functions, as introduced in Nested Functions, are a
convenient means of naming and defining self-contained blocks of
code as part of a larger function. However, it’s sometimes useful to
write shorter versions of function-like constructs without a full
declaration and name. This is particularly true when you work with
functions or methods that take functions as one or more of their
arguments.
If the first string (s1) is greater than the second string (s2), the
backward(_:_:) function will return true, indicating that s1 should
appear before s2 in the sorted array. For characters in strings,
“greater than” means “appears later in the alphabet than”. This
means that the letter "B" is “greater than” the letter "A", and the string
Note that the declaration of parameters and return type for this inline
closure is identical to the declaration from the backward(_:_:)
function. In both cases, it’s written as (s1: String, s2: String) ->
This illustrates that the overall call to the sorted(by:) method has
remained the same. A pair of parentheses still wrap the entire
argument for the method. However, that argument is now an inline
closure.
Nonetheless, you can still make the types explicit if you wish, and
doing so is encouraged if it avoids ambiguity for readers of your code.
In the case of the sorted(by:) method, the purpose of the closure is
clear from the fact that sorting is taking place, and it’s safe for a
reader to assume that the closure is likely to be working with String
values, because it’s assisting with the sorting of an array of strings.
Operator Methods
There’s actually an even shorter way to write the closure expression
above. Swift’s String type defines its string-specific implementation
of the greater-than operator (>) as a method that has two parameters
of type String, and returns a value of type Bool. This exactly matches
the method type needed by the sorted(by:) method. Therefore, you
can simply pass in the greater-than operator, and Swift will infer that
you want to use its string-specific implementation:
Trailing closures are most useful when the closure is sufficiently long
that it isn’t possible to write it inline on a single line. As an example,
Swift’s Array type has a map(_:) method, which takes a closure
expression as its single argument. The closure is called once for each
item in the array, and returns an alternative mapped value (possibly
of some other type) for that item. You specify the nature of the
mapping and the type of the returned value by writing code in the
closure that you pass to map(_:).
Here’s how you can use the map(_:) method with a trailing closure to
convert an array of Int values into an array of String values. The
array [16, 58, 510] is used to create the new array ["OneSix",
"FiveEight", "FiveOneZero"]:
1 let digitNames = [
2 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4:
"Four",
3 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9:
"Nine"
4 ]
5 let numbers = [16, 58, 510]
You can now use the numbers array to create an array of String
values, by passing a closure expression to the array’s map(_:)
method as a trailing closure:
The map(_:) method calls the closure expression once for each item
in the array. You don’t need to specify the type of the closure’s input
parameter, number, because the type can be inferred from the values
in the array to be mapped.
In this example, the variable number is initialized with the value of the
closure’s number parameter, so that the value can be modified within
the closure body. (The parameters to functions and closures are
always constants.) The closure expression also specifies a return
The closure expression builds a string called output each time it’s
called. It calculates the last digit of number by using the remainder
operator (number % 10), and uses this digit to look up an appropriate
string in the digitNames dictionary. The closure can be used to create
a string representation of any integer greater than zero.
NOTE
The number variable is then divided by 10. Because it’s an integer, it’s
rounded down during the division, so 16 becomes 1, 58 becomes 5,
and 510 becomes 51.
When you call this function to load a picture, you provide two
closures. The first closure is a completion handler that displays a
picture after a successful download. The second closure is an error
handler that displays an error to the user.
NOTE
Completion handlers can become hard to read, especially when you have to
nest multiple handlers. An alternate approach is to use asynchronous code,
as described in Concurrency.
Capturing Values
A closure can capture constants and variables from the surrounding
context in which it’s defined. The closure can then refer to and modify
the values of those constants and variables from within its body, even
if the original scope that defined the constants and variables no
longer exists.
NOTE
1 incrementByTen()
2 // returns a value of 40
NOTE
This also means that if you assign a closure to two different constants
or variables, both of those constants or variables refer to the same
closure.
Escaping Closures
1 struct SomeStruct {
2 var x = 10
3 mutating func doSomething() {
4 someFunctionWithNonescapingClosure { x = 200
} // Ok
5 someFunctionWithEscapingClosure { x = 100 }
// Error
6 }
7 }
Autoclosures
An autoclosure is a closure that’s automatically created to wrap an
expression that’s being passed as an argument to a function. It
doesn’t take any arguments, and when it’s called, it returns the value
of the expression that’s wrapped inside of it. This syntactic
convenience lets you omit braces around a function’s parameter by
writing a normal expression instead of an explicit closure.
It’s common to call functions that take autoclosures, but it’s not
common to implement that kind of function. For example, the
assert(condition:message:file:line:) function takes an
autoclosure for its condition and message parameters; its condition
parameter is evaluated only in debug builds and its message
parameter is evaluated only if condition is false.
You get the same behavior of delayed evaluation when you pass a
closure as an argument to a function.
Overusing autoclosures can make your code hard to understand. The context
and function name should make it clear that evaluation is being deferred.
If you are familiar with C, you will know that C enumerations assign
related names to a set of integer values. Enumerations in Swift are
much more flexible, and don’t have to provide a value for each case
of the enumeration. If a value (known as a raw value) is provided for
each enumeration case, the value can be a string, a character, or a
value of any integer or floating-point type.
1 enum SomeEnumeration {
2 // enumeration definition goes here
3 }
1 enum CompassPoint {
2 case north
3 case south
4 case east
5 case west
6 }
NOTE
Swift enumeration cases don’t have an integer value set by default, unlike
languages like C and Objective-C. In the CompassPoint example above,
north, south, east and west don’t implicitly equal 0, 1, 2 and 3. Instead, the
different enumeration cases are values in their own right, with an explicitly
defined type of CompassPoint.
directionToHead = .east
…and so on.
Associated Values
The examples in the previous section show how the cases of an
enumeration are a defined (and typed) value in their own right. You
can set a constant or variable to Planet.earth, and check for this
value later. However, it’s sometimes useful to be able to store values
of other types alongside these case values. This additional
information is called an associated value, and it varies each time you
use that case as a value in your code.
This definition doesn’t provide any actual Int or String values—it just
defines the type of associated values that Barcode constants and
variables can store when they’re equal to Barcode.upc or
Barcode.qrCode.
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
At this point, the original Barcode.upc and its integer values are
replaced by the new Barcode.qrCode and its string value. Constants
and variables of type Barcode can store either a .upc or a .qrCode
(together with their associated values), but they can store only one of
them at any given time.
1 switch productBarcode {
2 case .upc(let numberSystem, let manufacturer, let
product, let check):
3 print("UPC: \(numberSystem), \(manufacturer), \
(product), \(check).")
4 case .qrCode(let productCode):
5 print("QR code: \(productCode).")
6 }
7 // Prints "QR code: ABCDEFGHIJKLMNOP."
Raw Values
The barcode example in Associated Values shows how cases of an
enumeration can declare that they store associated values of
different types. As an alternative to associated values, enumeration
cases can come prepopulated with default values (called raw values),
which are all of the same type.
NOTE
Raw values are not the same as associated values. Raw values are set to
prepopulated values when you first define the enumeration in your code, like
the three ASCII codes above. The raw value for a particular enumeration case
is always the same. Associated values are set when you create a new
constant or variable based on one of the enumeration’s cases, and can be
different each time you do so.
For example, when integers are used for raw values, the implicit
value for each case is one more than the previous case. If the first
case doesn’t have a value set, its value is 0.
When strings are used for raw values, the implicit value for each case
is the text of that case’s name.
You access the raw value of an enumeration case with its rawValue
property:
Not all possible Int values will find a matching planet, however.
Because of this, the raw value initializer always returns an optional
enumeration case. In the example above, possiblePlanet is of type
Planet?, or “optional Planet.”
NOTE
The raw value initializer is a failable initializer, because not every raw value
will return an enumeration case. For more information, see Failable
Initializers.
If you try to find a planet with a position of 11, the optional Planet
value returned by the raw value initializer will be nil:
Recursive Enumerations
A recursive enumeration is an enumeration that has another instance
of the enumeration as the associated value for one or more of the
enumeration cases. You indicate that an enumeration case is
1 enum ArithmeticExpression {
2 case number(Int)
3 indirect case addition(ArithmeticExpression,
ArithmeticExpression)
4 indirect case
multiplication(ArithmeticExpression,
ArithmeticExpression)
5 }
You can also write indirect before the beginning of the enumeration
to enable indirection for all of the enumeration’s cases that have an
associated value:
NOTE
Classes and actors share many of the same characteristics and behaviors. For
information about actors, see Concurrency.
Definition Syntax
Structures and classes have a similar definition syntax. You introduce
structures with the struct keyword and classes with the class
keyword. Both place their entire definition within a pair of braces:
1 struct SomeStructure {
2 // structure definition goes here
3 }
4 class SomeClass {
5 // class definition goes here
6 }
NOTE
Whenever you define a new structure or class, you define a new Swift type.
Give types UpperCamelCase names (such as SomeStructure and SomeClass
here) to match the capitalization of standard Swift types (such as String, Int,
and Bool). Give properties and methods lowerCamelCase names (such as
frameRate and incrementCount) to differentiate them from type names.
The syntax for creating instances is very similar for both structures
and classes:
Structures and classes both use initializer syntax for new instances.
The simplest form of initializer syntax uses the type name of the class
or structure followed by empty parentheses, such as Resolution() or
VideoMode(). This creates a new instance of the class or structure,
with any properties initialized to their default values. Class and
structure initialization is described in more detail in Initialization.
Accessing Properties
You can access the properties of an instance using dot syntax. In dot
syntax, you write the property name immediately after the instance
name, separated by a period (.), without any spaces:
You can drill down into subproperties, such as the width property in
the resolution property of a VideoMode:
You can also use dot syntax to assign a new value to a variable
property:
1 someVideoMode.resolution.width = 1280
2 print("The width of someVideoMode is now \
(someVideoMode.resolution.width)")
3 // Prints "The width of someVideoMode is now 1280"
All structures and enumerations are value types in Swift. This means
that any structure and enumeration instances you create—and any
value types they have as properties—are always copied when they’re
passed around in your code.
NOTE
Collections defined by the standard library like arrays, dictionaries, and strings
use an optimization to reduce the performance cost of copying. Instead of
making a copy immediately, these collections share the memory where the
elements are stored between the original instance and any copies. If one of the
copies of the collection is modified, the elements are copied just before the
modification. The behavior you see in your code is always as if a copy took
place immediately.
Consider this example, which uses the Resolution structure from the
previous example:
cinema.width = 2048
However, the width property of the original hd instance still has the old
value of 1920:
When cinema was given the current value of hd, the values stored in hd
were copied into the new cinema instance. The end result was two
completely separate instances that contained the same numeric
values. However, because they’re separate instances, setting the
width of cinema to 2048 doesn’t affect the width stored in hd, as shown
in the figure below:
1 enum CompassPoint {
2 case north, south, east, west
3 mutating func turnNorth() {
4 self = .north
5 }
6 }
7 var currentDirection = CompassPoint.west
8 let rememberedDirection = currentDirection
9 currentDirection.turnNorth()
10
11 print("The current direction is \(currentDirection)")
12 print("The remembered direction is \
(rememberedDirection)")
13 // Prints "The current direction is north"
14 // Prints "The remembered direction is west"
Identity Operators
Because classes are reference types, it’s possible for multiple
constants and variables to refer to the same single instance of a class
behind the scenes. (The same isn’t true for structures and
enumerations, because they’re always copied when they’re assigned
to a constant or variable, or passed to a function.)
Identical to (===)
When you define your own custom structures and classes, it’s your
responsibility to decide what qualifies as two instances being equal.
The process of defining your own implementations of the == and !=
operators is described in Equivalence Operators.
Pointers
If you have experience with C, C++, or Objective-C, you may know
that these languages use pointers to refer to addresses in memory. A
Swift constant or variable that refers to an instance of some reference
type is similar to a pointer in C, but isn’t a direct pointer to an address
in memory, and doesn’t require you to write an asterisk (*) to indicate
that you are creating a reference. Instead, these references are
defined like any other constant or variable in Swift. The standard
library provides pointer and buffer types that you can use if you need
to interact with pointers directly—see Manual Memory Management.
You can also use a property wrapper to reuse code in the getter and
setter of multiple properties.
Stored Properties
In its simplest form, a stored property is a constant or variable that’s
stored as part of an instance of a particular class or structure. Stored
properties can be either variable stored properties (introduced by the
var keyword) or constant stored properties (introduced by the let
keyword).
1 struct FixedLengthRange {
2 var firstValue: Int
3 let length: Int
4 }
5 var rangeOfThreeItems = FixedLengthRange(firstValue:
0, length: 3)
6 // the range represents integer values 0, 1, and 2
7 rangeOfThreeItems.firstValue = 6
8 // the range now represents integer values 6, 7, and
8
The same isn’t true for classes, which are reference types. If you
assign an instance of a reference type to a constant, you can still
change that instance’s variable properties.
NOTE
You must always declare a lazy property as a variable (with the var keyword),
because its initial value might not be retrieved until after instance initialization
completes. Constant properties must always have a value before initialization
completes, and therefore can’t be declared as lazy.
1 print(manager.importer.filename)
2 // the DataImporter instance for the importer
property has now been created
3 // Prints "data.txt"
NOTE
Computed Properties
In addition to stored properties, classes, structures, and
enumerations can define computed properties, which don’t actually
store a value. Instead, they provide a getter and an optional setter to
retrieve and set other properties and values indirectly.
The example above creates a new Rect variable called square. The
square variable is initialized with an origin point of (0, 0), and a width
and height of 10. This square is represented by the light green square
in the diagram below.
The center property is then set to a new value of (15, 15), which
moves the square up and to the right, to the new position shown by
the dark green square in the diagram below. Setting the center
property calls the setter for center, which modifies the x and y values
of the stored origin property, and moves the square to its new
position.
1 struct AlternativeRect {
2 var origin = Point()
3 var size = Size()
4 var center: Point {
5 get {
6 let centerX = origin.x + (size.width /
2)
7 let centerY = origin.y + (size.height /
2)
8 return Point(x: centerX, y: centerY)
9 }
10 set {
11 origin.x = newValue.x - (size.width / 2)
12 origin.y = newValue.y - (size.height /
2)
13 }
14 }
15 }
1 struct CompactRect {
2 var origin = Point()
3 var size = Size()
4 var center: Point {
5 get {
6 Point(x: origin.x + (size.width / 2),
7 y: origin.y + (size.height / 2))
8 }
9 set {
10 origin.x = newValue.x - (size.width / 2)
11 origin.y = newValue.y - (size.height /
2)
12 }
13 }
14 }
Omitting the return from a getter follows the same rules as omitting
return from a function, as described in Functions With an Implicit
Return.
1 struct Cuboid {
2 var width = 0.0, height = 0.0, depth = 0.0
3 var volume: Double {
4 return width * height * depth
5 }
6 }
7 let fourByFiveByTwo = Cuboid(width: 4.0, height:
5.0, depth: 2.0)
8 print("the volume of fourByFiveByTwo is \
(fourByFiveByTwo.volume)")
9 // Prints "the volume of fourByFiveByTwo is 40.0"
NOTE
The willSet and didSet observers of superclass properties are called when
a property is set in a subclass initializer, after the superclass initializer has
been called. They aren’t called while a class is setting its own properties,
before the superclass initializer has been called.
For more information about initializer delegation, see Initializer Delegation for
Value Types and Initializer Delegation for Class Types.
NOTE
Property Wrappers
A property wrapper adds a layer of separation between code that
manages how a property is stored and the code that defines a
property. For example, if you have properties that provide thread-
safety checks or store their underlying data in a database, you have
to write that code on every property. When you use a property
wrapper, you write the management code once when you define the
1 @propertyWrapper
2 struct TwelveOrLess {
3 private var number = 0
4 var wrappedValue: Int {
5 get { return number }
6 set { number = min(newValue, 12) }
7 }
8 }
The setter ensures that new values are less than or equal to 12, and
the getter returns the stored value.
NOTE
The declaration for number in the example above marks the variable as
private, which ensures number is used only in the implementation of
TwelveOrLess. Code that’s written anywhere else accesses the value using
the getter and setter for wrappedValue, and can’t use number directly. For
information about private, see Access Control.
The height and width properties get their initial values from the
definition of TwelveOrLess, which sets TwelveOrLess.number to zero.
The setter in TwelveOrLess treats 10 as a valid value so storing the
number 10 in rectangle.height proceeds as written. However, 24 is
larger than TwelveOrLess allows, so trying to store 24 end up setting
rectangle.height to 12 instead, the largest allowed value.
1 struct SmallRectangle {
2 private var _height = TwelveOrLess()
3 private var _width = TwelveOrLess()
4 var height: Int {
5 get { return _height.wrappedValue }
6 set { _height.wrappedValue = newValue }
7 }
8 var width: Int {
9 get { return _width.wrappedValue }
10 set { _width.wrappedValue = newValue }
11 }
12 }
1 @propertyWrapper
2 struct SmallNumber {
3 private var maximum: Int
4 private var number: Int
5
6 var wrappedValue: Int {
7 get { return number }
8 set { number = min(newValue, maximum) }
9 }
10
11 init() {
12 maximum = 12
13 number = 0
14 }
15 init(wrappedValue: Int) {
16 maximum = 12
17 number = min(wrappedValue, maximum)
18 }
19 init(wrappedValue: Int, maximum: Int) {
20 self.maximum = maximum
21 number = min(wrappedValue, maximum)
22 }
23 }
1 struct ZeroRectangle {
2 @SmallNumber var height: Int
3 @SmallNumber var width: Int
4 }
5
6 var zeroRectangle = ZeroRectangle()
7 print(zeroRectangle.height, zeroRectangle.width)
8 // Prints "0 0"
When you specify an initial value for the property, Swift uses the
init(wrappedValue:) initializer to set up the wrapper. For example:
When you include property wrapper arguments, you can also specify
an initial value using assignment. Swift treats the assignment like a
1 struct MixedRectangle {
2 @SmallNumber var height: Int = 1
3 @SmallNumber(maximum: 9) var width: Int = 2
4 }
5
6 var mixedRectangle = MixedRectangle()
7 print(mixedRectangle.height)
8 // Prints "1"
9
10 mixedRectangle.height = 20
11 print(mixedRectangle.height)
12 // Prints "12"
When you access a projected value from code that’s part of the type,
like a property getter or an instance method, you can omit self.
before the property name, just like accessing other properties. The
code in the following example refers to the projected value of the
wrapper around height and width as $height and $width:
NOTE
You can apply a property wrapper to a local stored variable, but not to
a global variable or a computed variable. For example, in the code
1 func someFunction() {
2 @SmallNumber var myNumber: Int = 0
3
4 myNumber = 10
5 // now myNumber is 10
6
7 myNumber = 24
8 // now myNumber is 12
9 }
Type Properties
Instance properties are properties that belong to an instance of a
particular type. Every time you create a new instance of that type, it
has its own set of property values, separate from any other instance.
You can also define properties that belong to the type itself, not to any
one instance of that type. There will only ever be one copy of these
properties, no matter how many instances of that type you create.
These kinds of properties are called type properties.
Type properties are useful for defining values that are universal to all
instances of a particular type, such as a constant property that all
NOTE
Unlike stored instance properties, you must always give stored type properties
a default value. This is because the type itself doesn’t have an initializer that
can assign a value to a stored type property at initialization time.
Stored type properties are lazily initialized on their first access. They’re
guaranteed to be initialized only once, even when accessed by multiple
threads simultaneously, and they don’t need to be marked with the lazy
modifier.
You define type properties with the static keyword. For computed
type properties for class types, you can use the class keyword
instead to allow subclasses to override the superclass’s
implementation. The example below shows the syntax for stored and
computed type properties:
NOTE
The computed type property examples above are for read-only computed type
properties, but you can also define read-write computed type properties with
the same syntax as for computed instance properties.
1 print(SomeStructure.storedTypeProperty)
2 // Prints "Some value."
3 SomeStructure.storedTypeProperty = "Another value."
4 print(SomeStructure.storedTypeProperty)
5 // Prints "Another value."
6 print(SomeEnumeration.computedTypeProperty)
7 // Prints "6"
8 print(SomeClass.computedTypeProperty)
9 // Prints "27"
The examples that follow use two stored type properties as part of a
structure that models an audio level meter for a number of audio
channels. Each channel has an integer audio level between 0 and 10
inclusive.
The figure below illustrates how two of these audio channels can be
combined to model a stereo audio level meter. When a channel’s
audio level is 0, none of the lights for that channel are lit. When the
audio level is 10, all of the lights for that channel are lit. In this figure,
the left channel has a current level of 9, and the right channel has a
current level of 7:
NOTE
In the first of these two checks, the didSet observer sets currentLevel to a
different value. This doesn’t, however, cause the observer to be called again.
You can use the AudioChannel structure to create two new audio
channels called leftChannel and rightChannel, to represent the
audio levels of a stereo sound system:
If you set the currentLevel of the left channel to 7, you can see that
the maxInputLevelForAllChannels type property is updated to equal
7:
1 leftChannel.currentLevel = 7
2 print(leftChannel.currentLevel)
3 // Prints "7"
4 print(AudioChannel.maxInputLevelForAllChannels)
5 // Prints "7"
If you try to set the currentLevel of the right channel to 11, you can
see that the right channel’s currentLevel property is capped to the
maximum value of 10, and the maxInputLevelForAllChannels type
property is updated to equal 10:
1 rightChannel.currentLevel = 11
2 print(rightChannel.currentLevel)
3 // Prints "10"
4 print(AudioChannel.maxInputLevelForAllChannels)
5 // Prints "10"
Instance Methods
Instance methods are functions that belong to instances of a
particular class, structure, or enumeration. They support the
functionality of those instances, either by providing ways to access
and modify instance properties, or by providing functionality related to
the instance’s purpose. Instance methods have exactly the same
syntax as functions, as described in Functions.
You write an instance method within the opening and closing braces
of the type it belongs to. An instance method has implicit access to all
other instance methods and properties of that type. An instance
method can be called only on a specific instance of the type it
belongs to. It can’t be called in isolation without an existing instance.
1 class Counter {
2 var count = 0
3 func increment() {
4 count += 1
5 }
6 func increment(by amount: Int) {
7 count += amount
8 }
9 func reset() {
10 count = 0
11 }
12 }
You call instance methods with the same dot syntax as properties:
Function parameters can have both a name (for use within the
function’s body) and an argument label (for use when calling the
function), as described in Function Argument Labels and Parameter
Names. The same is true for method parameters, because methods
are just functions that are associated with a type.
1 func increment() {
2 self.count += 1
3 }
In practice, you don’t need to write self in your code very often. If you
don’t explicitly write self, Swift assumes that you are referring to a
property or method of the current instance whenever you use a
The main exception to this rule occurs when a parameter name for an
instance method has the same name as a property of that instance.
In this situation, the parameter name takes precedence, and it
becomes necessary to refer to the property in a more qualified way.
You use the self property to distinguish between the parameter
name and the property name.
1 struct Point {
2 var x = 0.0, y = 0.0
3 func isToTheRightOf(x: Double) -> Bool {
4 return self.x > x
5 }
6 }
7 let somePoint = Point(x: 4.0, y: 5.0)
8 if somePoint.isToTheRightOf(x: 1.0) {
9 print("This point is to the right of the line
where x == 1.0")
10 }
11 // Prints "This point is to the right of the line
where x == 1.0"
Without the self prefix, Swift would assume that both uses of x
referred to the method parameter called x.
1 struct Point {
2 var x = 0.0, y = 0.0
3 mutating func moveBy(x deltaX: Double, y deltaY:
Double) {
4 x += deltaX
5 y += deltaY
6 }
7 }
8 var somePoint = Point(x: 1.0, y: 1.0)
9 somePoint.moveBy(x: 2.0, y: 3.0)
10 print("The point is now at (\(somePoint.x), \
(somePoint.y))")
11 // Prints "The point is now at (3.0, 4.0)"
1 struct Point {
2 var x = 0.0, y = 0.0
3 mutating func moveBy(x deltaX: Double, y deltaY:
Double) {
4 self = Point(x: x + deltaX, y: y + deltaY)
5 }
6 }
1 enum TriStateSwitch {
2 case off, low, high
3 mutating func next() {
4 switch self {
5 case .off:
6 self = .low
7 case .low:
8 self = .high
9 case .high:
10 self = .off
11 }
12 }
13 }
14 var ovenLight = TriStateSwitch.low
15 ovenLight.next()
16 // ovenLight is now equal to .high
17 ovenLight.next()
18 // ovenLight is now equal to .off
NOTE
Type methods are called with dot syntax, like instance methods.
However, you call type methods on the type, not on an instance of
that type. Here’s how you call a type method on a class called
SomeClass:
1 class SomeClass {
2 class func someTypeMethod() {
3 // type method implementation goes here
4 }
5 }
6 SomeClass.someTypeMethod()
Within the body of a type method, the implicit self property refers to
the type itself, rather than an instance of that type. This means that
you can use self to disambiguate between type properties and type
method parameters, just as you do for instance properties and
instance method parameters.
All of the game’s levels (apart from level one) are locked when the
game is first played. Every time a player finishes a level, that level is
unlocked for all players on the device. The LevelTracker structure
uses type properties and methods to keep track of which levels of the
game have been unlocked. It also tracks the current level for an
individual player.
The LevelTracker structure keeps track of the highest level that any
player has unlocked. This value is stored in a type property called
highestUnlockedLevel.
You can create an instance of the Player class for a new player, and
see what happens when the player completes level one:
You can define multiple subscripts for a single type, and the
appropriate subscript overload to use is selected based on the type of
index value you pass to the subscript. Subscripts aren’t limited to a
single dimension, and you can define subscripts with multiple input
parameters to suit your custom type’s needs.
Subscript Syntax
Subscripts enable you to query instances of a type by writing one or
more values in square brackets after the instance name. Their syntax
is similar to both instance method syntax and computed property
syntax. You write subscript definitions with the subscript keyword,
and specify one or more input parameters and a return type, in the
same way as instance methods. Unlike instance methods, subscripts
can be read-write or read-only. This behavior is communicated by a
getter and setter in the same way as for computed properties:
The type of newValue is the same as the return value of the subscript.
As with computed properties, you can choose not to specify the
setter’s (newValue) parameter. A default parameter called newValue
is provided to your setter if you don’t provide one yourself.
NOTE
Subscript Usage
The exact meaning of “subscript” depends on the context in which it’s
used. Subscripts are typically used as a shortcut for accessing the
NOTE
Subscript Options
The example above creates a new Matrix instance with two rows and
two columns. The grid array for this Matrix instance is effectively a
flattened version of the matrix, as read from top left to bottom right:
1 matrix[0, 1] = 1.5
2 matrix[1, 0] = 3.2
These two statements call the subscript’s setter to set a value of 1.5
in the top right position of the matrix (where row is 0 and column is 1),
and 3.2 in the bottom left position (where row is 1 and column is 0):
Type Subscripts
Instance subscripts, as described above, are subscripts that you call
on an instance of a particular type. You can also define subscripts
that are called on the type itself. This kind of subscript is called a type
subscript. You indicate a type subscript by writing the static keyword
before the subscript keyword. Classes can use the class keyword
instead, to allow subclasses to override the superclass’s
implementation of that subscript. The example below shows how you
define and call a type subscript:
NOTE
Swift classes don’t inherit from a universal base class. Classes you define
without specifying a superclass automatically become base classes for you to
build upon.
The Vehicle base class also defines a method called makeNoise. This
method doesn’t actually do anything for a base Vehicle instance, but
will be customized by subclasses of Vehicle later on:
1 class Vehicle {
2 var currentSpeed = 0.0
3 var description: String {
4 return "traveling at \(currentSpeed) miles
per hour"
5 }
6 func makeNoise() {
7 // do nothing - an arbitrary vehicle doesn't
necessarily make a noise
8 }
9 }
Subclassing
Subclassing is the act of basing a new class on an existing class. The
subclass inherits characteristics from the existing class, which you
can then refine. You can also add new characteristics to the subclass.
By default, any new Bicycle instance you create will not have a
basket. You can set the hasBasket property to true for a particular
Bicycle instance after that instance is created:
1 bicycle.currentSpeed = 15.0
2 print("Bicycle: \(bicycle.description)")
3 // Bicycle: traveling at 15.0 miles per hour
Tandem inherits all of the properties and methods from Bicycle, which
in turn inherits all of the properties and methods from Vehicle. The
Tandem subclass also adds a new stored property called
currentNumberOfPassengers, with a default value of 0.
Overriding
A subclass can provide its own custom implementation of an instance
method, type method, instance property, type property, or subscript
that it would otherwise inherit from a superclass. This is known as
overriding.
The override keyword also prompts the Swift compiler to check that
your overriding class’s superclass (or one of its parents) has a
declaration that matches the one you provided for the override. This
check ensures that your overriding definition is correct.
Overriding Methods
You can override an inherited instance or type method to provide a
tailored or alternative implementation of the method within your
subclass.
Overriding Properties
You can override an inherited instance or type property to provide
your own custom getter and setter for that property, or to add
property observers to enable the overriding property to observe when
the underlying property value changes.
NOTE
If you provide a setter as part of a property override, you must also provide a
getter for that override. If you don’t want to modify the inherited property’s
value within the overriding getter, you can simply pass through the inherited
value by returning super.someProperty from the getter, where
someProperty is the name of the property you are overriding.
NOTE
Preventing Overrides
You can prevent a method, property, or subscript from being
overridden by marking it as final. Do this by writing the final modifier
before the method, property, or subscript’s introducer keyword (such
as final var, final func, final class func, and final subscript).
You can mark an entire class as final by writing the final modifier
before the class keyword in its class definition (final class). Any
attempt to subclass a final class is reported as a compile-time error.
You can set an initial value for a stored property within an initializer, or
by assigning a default property value as part of the property’s
definition. These actions are described in the following sections.
When you assign a default value to a stored property, or set its initial value
within an initializer, the value of that property is set directly, without calling any
property observers.
Initializers
Initializers are called to create a new instance of a particular type. In
its simplest form, an initializer is like an instance method with no
parameters, written using the init keyword:
1 init() {
2 // perform some initialization here
3 }
If a property always takes the same initial value, provide a default value rather
than setting a value within an initializer. The end result is the same, but the
default value ties the property’s initialization more closely to its declaration. It
makes for shorter, clearer initializers and enables you to infer the type of the
property from its default value. The default value also makes it easier for you
to take advantage of default initializers and initializer inheritance, as described
later in this chapter.
You can write the Fahrenheit structure from above in a simpler form
by providing a default value for its temperature property at the point
that the property is declared:
1 struct Fahrenheit {
2 var temperature = 32.0
3 }
Customizing Initialization
You can customize the initialization process with input parameters
and optional property types, or by assigning constant properties
during initialization, as described in the following sections.
Initialization Parameters
You can provide initialization parameters as part of an initializer’s
definition, to define the types and names of values that customize the
initialization process. Initialization parameters have the same
capabilities and syntax as function and method parameters.
1 struct Celsius {
2 var temperatureInCelsius: Double
3 init(fromFahrenheit fahrenheit: Double) {
4 temperatureInCelsius = (fahrenheit - 32.0) /
1.8
5 }
6 init(fromKelvin kelvin: Double) {
7 temperatureInCelsius = kelvin - 273.15
8 }
9 }
10 let boilingPointOfWater = Celsius(fromFahrenheit:
212.0)
11 // boilingPointOfWater.temperatureInCelsius is 100.0
12 let freezingPointOfWater = Celsius(fromKelvin:
273.15)
13 // freezingPointOfWater.temperatureInCelsius is 0.0
1 struct Celsius {
2 var temperatureInCelsius: Double
3 init(fromFahrenheit fahrenheit: Double) {
4 temperatureInCelsius = (fahrenheit - 32.0) /
1.8
5 }
6 init(fromKelvin kelvin: Double) {
7 temperatureInCelsius = kelvin - 273.15
8 }
9 init(_ celsius: Double) {
10 temperatureInCelsius = celsius
11 }
12 }
13 let bodyTemperature = Celsius(37.0)
14 // bodyTemperature.temperatureInCelsius is 37.0
The initializer call Celsius(37.0) is clear in its intent without the need
for an argument label. It’s therefore appropriate to write this initializer
as init(_ celsius: Double) so that it can be called by providing an
unnamed Double value.
1 class SurveyQuestion {
2 var text: String
3 var response: String?
4 init(text: String) {
5 self.text = text
6 }
7 func ask() {
8 print(text)
9 }
10 }
11 let cheeseQuestion = SurveyQuestion(text: "Do you
like cheese?")
12 cheeseQuestion.ask()
13 // Prints "Do you like cheese?"
14 cheeseQuestion.response = "Yes, I do like cheese."
NOTE
Default Initializers
Swift provides a default initializer for any structure or class that
provides default values for all of its properties and doesn’t provide at
least one initializer itself. The default initializer simply creates a new
instance with all of its properties set to their default values.
1 struct Size {
2 var width = 0.0, height = 0.0
3 }
4 let twoByTwo = Size(width: 2.0, height: 2.0)
When you call a memberwise initializer, you can omit values for any
properties that have default values. In the example above, the Size
structure has a default value for both its height and width properties.
You can omit either property or both properties, and the initializer
uses the default value for anything you omit. For example:
The rules for how initializer delegation works, and for what forms of
delegation are allowed, are different for value types and class types.
Value types (structures and enumerations) don’t support inheritance,
and so their initializer delegation process is relatively simple, because
they can only delegate to another initializer that they provide
themselves. Classes, however, can inherit from other classes, as
described in Inheritance. This means that classes have additional
responsibilities for ensuring that all stored properties they inherit are
assigned a suitable value during initialization. These responsibilities
are described in Class Inheritance and Initialization below.
For value types, you use self.init to refer to other initializers from
the same value type when writing your own custom initializers. You
can call self.init only from within an initializer.
Note that if you define a custom initializer for a value type, you will no
longer have access to the default initializer (or the memberwise
initializer, if it’s a structure) for that type. This constraint prevents a
situation in which additional essential setup provided in a more
complex initializer is accidentally circumvented by someone using
one of the automatic initializers.
NOTE
If you want your custom value type to be initializable with the default initializer
and memberwise initializer, and also with your own custom initializers, write
your custom initializers in an extension rather than as part of the value type’s
original implementation. For more information, see Extensions.
You can initialize the Rect structure below in one of three ways—by
using its default zero-initialized origin and size property values, by
providing a specific origin point and size, or by providing a specific
center point and size. These initialization options are represented by
three custom initializers that are part of the Rect structure’s definition:
The first Rect initializer, init(), is functionally the same as the default
initializer that the structure would have received if it didn’t have its
own custom initializers. This initializer has an empty body,
represented by an empty pair of curly braces {}. Calling this initializer
returns a Rect instance whose origin and size properties are both
initialized with the default values of Point(x: 0.0, y: 0.0) and
Size(width: 0.0, height: 0.0) from their property definitions:
For an alternative way to write this example without defining the init() and
init(origin:size:) initializers yourself, see Extensions.
Swift defines two kinds of initializers for class types to help ensure all
stored properties receive an initial value. These are known as
designated initializers and convenience initializers.
Classes tend to have very few designated initializers, and it’s quite
common for a class to have only one. Designated initializers are
“funnel” points through which initialization takes place, and through
which the initialization process continues up the superclass chain.
init( parameters ) {
statements
}
Convenience initializers are written in the same style, but with the
convenience modifier placed before the init keyword, separated by
a space:
Rule 1
Rule 2
Rule 3
The subclass in this figure has two designated initializers and one
convenience initializer. The convenience initializer must call one of
the two designated initializers, because it can only call another
initializer from the same class. This satisfies rules 2 and 3 from
above. Both designated initializers must call the single designated
initializer from the superclass, to satisfy rule 1 from above.
NOTE
These rules don’t affect how users of your classes create instances of each
class. Any initializer in the diagram above can be used to create a fully
initialized instance of the class they belong to. The rules only affect how you
write the implementation of the class’s initializers.
The figure below shows a more complex class hierarchy for four
classes. It illustrates how the designated initializers in this hierarchy
act as “funnel” points for class initialization, simplifying the
interrelationships among classes in the chain:
Safety check 1
Safety check 2
Safety check 3
The class instance isn’t fully valid until the first phase ends.
Properties can only be accessed, and methods can only be called,
once the class instance is known to be valid at the end of the first
phase.
Phase 1
This continues up the class inheritance chain until the top of the
chain is reached.
Once the top of the chain is reached, and the final class in the
chain has ensured that all of its stored properties have a value,
the instance’s memory is considered to be fully initialized, and
phase 1 is complete.
Phase 2
NOTE
1 class Vehicle {
2 var numberOfWheels = 0
3 var description: String {
4 return "\(numberOfWheels) wheel(s)"
5 }
6 }
The Vehicle class provides a default value for its only stored
property, and doesn’t provide any custom initializers itself. As a
result, it automatically receives a default initializer, as described in
Default Initializers. The default initializer (when available) is always a
designated initializer for a class, and can be used to create a new
Vehicle instance with a numberOfWheels of 0:
Assuming that you provide default values for any new properties you
introduce in a subclass, the following two rules apply:
Rule 1
Rule 2
NOTE
The base class in the hierarchy is called Food, which is a simple class
to encapsulate the name of a foodstuff. The Food class introduces a
single String property called name and provides two initializers for
creating Food instances:
1 class Food {
2 var name: String
3 init(name: String) {
4 self.name = name
5 }
6 convenience init() {
7 self.init(name: "[Unnamed]")
8 }
9 }
The figure below shows the initializer chain for the Food class:
The figure below shows the initializer chain for the RecipeIngredient
class:
The figure below shows the overall initializer chain for all three
classes:
Failable Initializers
It’s sometimes useful to define a class, structure, or enumeration for
which initialization can fail. This failure might be triggered by invalid
initialization parameter values, the absence of a required external
To cope with initialization conditions that can fail, define one or more
failable initializers as part of a class, structure, or enumeration
definition. You write a failable initializer by placing a question mark
after the init keyword (init?).
NOTE
You can’t define a failable and a nonfailable initializer with the same
parameter types and names.
NOTE
Strictly speaking, initializers don’t return a value. Rather, their role is to ensure
that self is fully and correctly initialized by the time that initialization ends.
Although you write return nil to trigger an initialization failure, you don’t use
the return keyword to indicate initialization success.
You can use this failable initializer to try to initialize a new Animal
instance and to check if initialization succeeded:
NOTE
Checking for an empty string value (such as "" rather than "Giraffe") isn’t
the same as checking for nil to indicate the absence of an optional String
value. In the example above, an empty string ("") is a valid, non-optional
String. However, it’s not appropriate for an animal to have an empty string as
the value of its species property. To model this restriction, the failable
initializer triggers an initialization failure if an empty string is found.
You can rewrite the TemperatureUnit example from above to use raw
values of type Character and to take advantage of the init?
(rawValue:) initializer:
NOTE
NOTE
You can override a failable initializer with a nonfailable initializer but not the
other way around.
You can delegate from init? to init! and vice versa, and you can
override init? with init! and vice versa. You can also delegate from
init to init!, although doing so will trigger an assertion if the init!
initializer causes initialization to fail.
Required Initializers
Write the required modifier before the definition of a class initializer
to indicate that every subclass of the class must implement that
1 class SomeClass {
2 required init() {
3 // initializer implementation goes here
4 }
5 }
You must also write the required modifier before every subclass
implementation of a required initializer, to indicate that the initializer
requirement applies to further subclasses in the chain. You don’t write
the override modifier when overriding a required designated
initializer:
NOTE
1 class SomeClass {
2 let someProperty: SomeType = {
3 // create a default value for someProperty
inside this closure
4 // someValue must be of the same type as
SomeType
5 return someValue
6 }()
7 }
Note that the closure’s end curly brace is followed by an empty pair of
parentheses. This tells Swift to execute the closure immediately. If
you omit these parentheses, you are trying to assign the closure itself
to the property, and not the return value of the closure.
If you use a closure to initialize a property, remember that the rest of the
instance hasn’t yet been initialized at the point that the closure is executed.
This means that you can’t access any other property values from within your
closure, even if those properties have default values. You also can’t use the
implicit self property, or call any of the instance’s methods.
Class definitions can have at most one deinitializer per class. The
deinitializer doesn’t take any parameters and is written without
parentheses:
1 deinit {
2 // perform the deinitialization
3 }
Deinitializers in Action
Here’s an example of a deinitializer in action. This example defines
two new types, Bank and Player, for a simple game. The Bank class
manages a made-up currency, which can never have more than
10,000 coins in circulation. There can only ever be one Bank in the
game, and so the Bank is implemented as a class with type properties
and methods to store and manage its current state:
Bank keeps track of the current number of coins it holds with its
coinsInBank property. It also offers two methods—
distribute(coins:) and receive(coins:)—to handle the distribution
and collection of coins.
The Player class describes a player in the game. Each player has a
certain number of coins stored in their purse at any time. This is
represented by the player’s coinsInPurse property:
1 playerOne!.win(coins: 2_000)
2 print("PlayerOne won 2000 coins & now has \
(playerOne!.coinsInPurse) coins")
3 // Prints "PlayerOne won 2000 coins & now has 2100
coins"
4 print("The bank now only has \(Bank.coinsInBank)
coins left")
5 // Prints "The bank now only has 7900 coins left"
1 playerOne = nil
2 print("PlayerOne has left the game")
3 // Prints "PlayerOne has left the game"
4 print("The bank now has \(Bank.coinsInBank) coins")
5 // Prints "The bank now has 10000 coins"
The player has now left the game. This is indicated by setting the
optional playerOne variable to nil, meaning “no Player instance.” At
the point that this happens, the playerOne variable’s reference to the
Player instance is broken. No other properties or variables are still
referring to the Player instance, and so it’s deallocated in order to
free up its memory. Just before this happens, its deinitializer is called
automatically, and its coins are returned to the bank.
NOTE
To reflect the fact that optional chaining can be called on a nil value,
the result of an optional chaining call is always an optional value,
even if the property, method, or subscript you are querying returns a
non-optional value. You can use this optional return value to check
whether the optional chaining call was successful (the returned
optional contains a value), or didn’t succeed due to a nil value in the
chain (the returned optional value is nil).
1 class Person {
2 var residence: Residence?
3 }
4
5 class Residence {
6 var numberOfRooms = 1
7 }
john.residence = Residence()
1 class Person {
2 var residence: Residence?
3 }
The Residence class is more complex than before. This time, the
Residence class defines a variable property called rooms, which is
initialized with an empty array of type [Room]:
The Room class used for the rooms array is a simple class with one
property called name, and an initializer to set that property to a
suitable room name:
1 class Room {
2 let name: String
3 init(name: String) { self.name = name }
4 }
The final class in this model is called Address. This class has three
optional properties of type String?. The first two properties,
buildingName and buildingNumber, are alternative ways to identify a
particular building as part of an address. The third property, street, is
used to name the street for that address:
You can tell that the createAddress() function isn’t called, because
nothing is printed.
If you call this method on an optional value with optional chaining, the
method’s return type will be Void?, not Void, because return values
are always of an optional type when called through optional chaining.
This enables you to use an if statement to check whether it was
possible to call the printNumberOfRooms() method, even though the
method doesn’t itself define a return value. Compare the return value
from the printNumberOfRooms call against nil to see if the method
call was successful:
1 if john.residence?.printNumberOfRooms() != nil {
2 print("It was possible to print the number of
rooms.")
3 } else {
4 print("It was not possible to print the number
of rooms.")
5 }
6 // Prints "It was not possible to print the number
of rooms."
NOTE
The example below tries to retrieve the name of the first room in the
rooms array of the john.residence property using the subscript
defined on the Residence class. Because john.residence is currently
nil, the subscript call fails:
Similarly, you can try to set a new value through a subscript with
optional chaining:
If the type you are trying to retrieve isn’t optional, it will become
optional because of the optional chaining.
If the type you are trying to retrieve is already optional, it will not
become more optional because of the chaining.
Therefore:
Note that in the example above, you are trying to retrieve the value of
the street property. The type of this property is String?. The return
value of john.residence?.address?.street is therefore also
String?, even though two levels of optional chaining are applied in
addition to the underlying optional type of the property.
1 if let beginsWithThe =
2
john.residence?.address?.buildingIdentifier()?.
hasPrefix("The") {
3 if beginsWithThe {
4 print("John's building identifier begins
with \"The\".")
5 } else {
6 print("John's building identifier doesn't
begin with \"The\".")
7 }
8 }
9 // Prints "John's building identifier begins with
"The"."
In the example above, you place the optional chaining question mark after the
parentheses, because the optional value you are chaining on is the
buildingIdentifier() method’s return value, and not the
buildingIdentifier() method itself.
NOTE
Error handling in Swift interoperates with error handling patterns that use the
NSError class in Cocoa and Objective-C. For more information about this
class, see Handling Cocoa Errors in Swift.
throw
VendingMachineError.insufficientFunds(coinsNeed
ed: 5)
Handling Errors
When an error is thrown, some surrounding piece of code must be
responsible for handling the error—for example, by correcting the
problem, trying an alternative approach, or informing the user of the
failure.
NOTE
NOTE
Only throwing functions can propagate errors. Any errors thrown inside a
nonthrowing function must be handled inside the function.
You write a pattern after catch to indicate what errors that clause can
handle. If a catch clause doesn’t have a pattern, the clause matches
any error and binds the error to a local constant named error. For
more information about pattern matching, see Patterns.
For example, the following code matches against all three cases of
the VendingMachineError enumeration.
For example, the above example can be written so any error that isn’t
a VendingMachineError is instead caught by the calling function:
Another way to catch several related errors is to list them after catch,
separated by commas. For example:
Using try? lets you write concise error handling code when you want
to handle all errors in the same way. For example, the following code
uses several approaches to fetch data, or returns nil if all of the
approaches fail.
NOTE
You can use a defer statement even when no error handling code is involved.
Swift has built-in support for writing asynchronous and parallel code
in a structured way. Asynchronous code can be suspended and
resumed later, although only one piece of the program executes at a
time. Suspending and resuming code in your program lets it continue
to make progress on short-term operations like updating its UI while
continuing to work on long-running operations like fetching data over
the network or parsing files. Parallel code means multiple pieces of
code run simultaneously—for example, a computer with a four-core
processor can run four pieces of code at the same time, with each
core carrying out one of the tasks. A program that uses parallel and
asynchronous code carries out multiple operations at a time; it
suspends operations that are waiting for an external system, and
makes it easier to write this code in a memory-safe way.
The rest of this chapter uses the term concurrency to refer to this
common combination of asynchronous and parallel code.
If you’ve written concurrent code before, you might be used to working with
threads. The concurrency model in Swift is built on top of threads, but you
don’t interact with them directly. An asynchronous function in Swift can give
up the thread that it’s running on, which lets another asynchronous function
run on that thread while the first function is blocked. When an asynchronous
function resumes, Swift doesn’t make any guarantee about which thread that
function will run on.
For example, the code below fetches the names of all the pictures in
a gallery and then shows the first picture:
1. The code starts running from the first line and runs up to the first
await. It calls the listPhotos(inGallery:) function and
suspends execution while it waits for that function to return.
NOTE
Asynchronous Sequences
The listPhotos(inGallery:) function in the previous section
asynchronously returns the whole array at once, after all of the
array’s elements are ready. Another approach is to wait for one
element of the collection at a time using an asynchronous sequence.
Here’s what iterating over an asynchronous sequence looks like:
In the same way that you can use your own types in a for-in loop by
adding conformance to the Sequence protocol, you can use your own
types in a for-await-in loop by adding conformance to the
AsyncSequence protocol.
Here’s how you can think about the differences between these two
approaches:
You can also mix both of these approaches in the same code.
Tasks are arranged in a hierarchy. Each task in a task group has the
same parent task, and each task can have child tasks. Because of
the explicit relationship between tasks and task groups, this approach
is called structured concurrency. Although you take on some of the
responsibility for correctness, the explicit parent-child relationships
between tasks lets Swift handle some behaviors like propagating
cancellation for you, and lets Swift detect some errors at compile
time.
Unstructured Concurrency
In addition to the structured approaches to concurrency described in
the previous sections, Swift also supports unstructured concurrency.
Unlike tasks that are part of a task group, an unstructured task
doesn’t have a parent task. You have complete flexibility to manage
unstructured tasks in whatever way your program needs, but you’re
also completely responsible for their correctness. To create an
unstructured task that runs on the current actor, call the
Task.init(priority:operation:) initializer. To create an
unstructured task that’s not part of the current actor, known more
specifically as a detached task, call the
Task.detached(priority:operation:) class method. Both of these
operations return a task that you can interact with—for example, to
wait for its result or to cancel it.
Task Cancellation
Swift concurrency uses a cooperative cancellation model. Each task
checks whether it has been canceled at the appropriate points in its
execution, and responds to cancellation in whatever way is
appropriate. Depending on the work you’re doing, that usually means
one of the following:
1 actor TemperatureLogger {
2 let label: String
3 var measurements: [Int]
4 private(set) var max: Int
5
6 init(label: String, measurement: Int) {
7 self.label = label
8 self.measurements = [measurement]
9 self.max = measurement
10 }
11 }
In contrast, code that’s part of the actor doesn’t write await when
accessing the actor’s properties. For example, here’s a method that
updates a TemperatureLogger with a new temperature:
1 extension TemperatureLogger {
2 func update(with measurement: Int) {
3 measurements.append(measurement)
4 if measurement > max {
5 max = measurement
6 }
7 }
8 }
2. Before your code can update max, code elsewhere reads the
maximum value and the array of temperatures.
If you try to access those properties from outside the actor, like you
would with an instance of a class, you’ll get a compile-time error. For
example:
print(logger.max) // Error
Sendable Types
Tasks and actors let you divide a program into pieces that can safely
run concurrently. Inside of a task or an instance of an actor, the part
of a program that contains mutable state, like variables and
properties, is called a concurrency domain. Some kinds of data can’t
be shared between concurrency domains, because that data
contains mutable state, but it doesn’t protect against overlapping
access.
The type doesn’t have any mutable state, and its immutable
state is made up of other sendable data—for example, a
structure or class that has only read-only properties.
The type has code that ensures the safety of its mutable state,
like a class that’s marked @MainActor or a class that serializes
access to its properties on a particular thread or queue.
Some types are always sendable, like structures that have only
sendable properties and enumerations that have only sendable
associated values. For example:
1 struct TemperatureReading {
2 var measurement: Int
3 }
You can also use type casting to check whether a type conforms to a
protocol, as described in Checking for Protocol Conformance.
The first snippet defines a new base class called MediaItem. This
class provides basic functionality for any kind of item that appears in
a digital media library. Specifically, it declares a name property of type
String, and an init name initializer. (It’s assumed that all media
items, including all movies and songs, will have a name.)
The items stored in library are still Movie and Song instances behind
the scenes. However, if you iterate over the contents of this array, the
items you receive back are typed as MediaItem, and not as Movie or
Song. In order to work with them as their native type, you need to
check their type, or downcast them to a different type, as described
below.
Checking Type
Use the type check operator (is) to check whether an instance is of a
certain subclass type. The type check operator returns true if the
instance is of that subclass type and false if it’s not.
1 var movieCount = 0
2 var songCount = 0
3
4 for item in library {
5 if item is Movie {
6 movieCount += 1
7 } else if item is Song {
8 songCount += 1
9 }
10 }
11
12 print("Media library contains \(movieCount) movies
and \(songCount) songs")
13 // Prints "Media library contains 2 movies and 3
songs"
This example iterates through all items in the library array. On each
pass, the for-in loop sets the item constant to the next MediaItem in
the array.
Because downcasting can fail, the type cast operator comes in two
different forms. The conditional form, as?, returns an optional value of
the type you are trying to downcast to. The forced form, as!, attempts
the downcast and force-unwraps the result as a single compound
action.
Use the conditional form of the type cast operator (as?) when you
aren’t sure if the downcast will succeed. This form of the operator will
always return an optional value, and the value will be nil if the
downcast was not possible. This enables you to check for a
successful downcast.
Use the forced form of the type cast operator (as!) only when you are
sure that the downcast will always succeed. This form of the operator
will trigger a runtime error if you try to downcast to an incorrect class
type.
NOTE
Casting doesn’t actually modify the instance or change its values. The
underlying instance remains the same; it’s simply treated and accessed as an
instance of the type to which it has been cast.
Use Any and AnyObject only when you explicitly need the behavior
and capabilities they provide. It’s always better to be specific about
the types you expect to work with in your code.
The things array contains two Int values, two Double values, a
String value, a tuple of type (Double, Double), the movie
“Ghostbusters”, and a closure expression that takes a String value
and returns another String value.
NOTE
The Any type represents values of any type, including optional types. Swift
gives you a warning if you use an optional value where a value of type Any is
expected. If you really do need to use an optional value as an Any value, you
can use the as operator to explicitly cast the optional to Any, as shown below.
To nest a type within another type, write its definition within the outer
braces of the type it supports. Types can be nested to as many levels
as are required.
In Blackjack, the Ace cards have a value of either one or eleven. This
feature is represented by a structure called Values, which is nested
within the Rank enumeration:
The Suit enumeration describes the four common playing card suits,
together with a raw Character value to represent their symbol.
Even though Rank and Suit are nested within BlackjackCard, their
type can be inferred from context, and so the initialization of this
instance is able to refer to the enumeration cases by their case
names (.ace and .spades) alone. In the example above, the
description property correctly reports that the Ace of Spades has a
value of 1 or 11.
1 let heartsSymbol =
BlackjackCard.Suit.hearts.rawValue
2 // heartsSymbol is "♡"
For the example above, this enables the names of Suit, Rank, and
Values to be kept deliberately short, because their names are
naturally qualified by the context in which they’re defined.
Define subscripts
NOTE
Extensions can add new functionality to a type, but they can’t override existing
functionality.
1 extension SomeType {
2 // new functionality to add to SomeType goes
here
3 }
NOTE
If you define an extension to add new functionality to an existing type, the new
functionality will be available on all existing instances of that type, even if they
were created before the extension was defined.
1 extension Double {
2 var km: Double { return self * 1_000.0 }
3 var m: Double { return self }
4 var cm: Double { return self / 100.0 }
5 var mm: Double { return self / 1_000.0 }
6 var ft: Double { return self / 3.28084 }
7 }
8 let oneInch = 25.4.mm
9 print("One inch is \(oneInch) meters")
10 // Prints "One inch is 0.0254 meters"
11 let threeFeet = 3.ft
12 print("Three feet is \(threeFeet) meters")
13 // Prints "Three feet is 0.914399970739201 meters"
NOTE
Extensions can add new computed properties, but they can’t add stored
properties, or add property observers to existing properties.
Initializers
Extensions can add new initializers to existing types. This enables
you to extend other types to accept your own custom types as
initializer parameters, or to provide additional initialization options
that were not included as part of the type’s original implementation.
1 struct Size {
2 var width = 0.0, height = 0.0
3 }
4 struct Point {
5 var x = 0.0, y = 0.0
6 }
7 struct Rect {
8 var origin = Point()
9 var size = Size()
10 }
Because the Rect structure provides default values for all of its
properties, it receives a default initializer and a memberwise initializer
automatically, as described in Default Initializers. These initializers
can be used to create new Rect instances:
1 extension Rect {
2 init(center: Point, size: Size) {
3 let originX = center.x - (size.width / 2)
4 let originY = center.y - (size.height / 2)
5 self.init(origin: Point(x: originX, y:
originY), size: size)
6 }
7 }
If you provide a new initializer with an extension, you are still responsible for
making sure that each instance is fully initialized once the initializer
completes.
Methods
Extensions can add new instance methods and type methods to
existing types. The following example adds a new instance method
called repetitions to the Int type:
1 extension Int {
2 func repetitions(task: () -> Void) {
3 for _ in 0..<self {
4 task()
5 }
6 }
7 }
1 extension Int {
2 mutating func square() {
3 self = self * self
4 }
5 }
6 var someInt = 3
7 someInt.square()
8 // someInt is now 9
Subscripts
123456789[0] returns 9
123456789[1] returns 8
…and so on:
1 extension Int {
2 subscript(digitIndex: Int) -> Int {
3 var decimalBase = 1
4 for _ in 0..<digitIndex {
5 decimalBase *= 10
6 }
7 return (self / decimalBase) % 10
8 }
9 }
10 746381295[0]
11 // returns 5
12 746381295[1]
13 // returns 9
14 746381295[2]
15 // returns 2
16 746381295[8]
17 // returns 7
1 746381295[9]
2 // returns 0, as if you had requested:
3 0746381295[9]
Nested Types
Extensions can add new nested types to existing classes, structures,
and enumerations:
The nested enumeration can now be used with any Int value:
NOTE
Protocol Syntax
You define protocols in a very similar way to classes, structures, and
enumerations:
1 protocol SomeProtocol {
2 // protocol definition goes here
3 }
Property Requirements
A protocol can require any conforming type to provide an instance
property or type property with a particular name and type. The
protocol doesn’t specify whether the property should be a stored
property or a computed property—it only specifies the required
property name and type. The protocol also specifies whether each
property must be gettable or gettable and settable.
1 protocol SomeProtocol {
2 var mustBeSettable: Int { get set }
3 var doesNotNeedToBeSettable: Int { get }
4 }
1 protocol AnotherProtocol {
2 static var someTypeProperty: Int { get set }
3 }
1 protocol FullyNamed {
2 var fullName: String { get }
3 }
Here’s a more complex class, which also adopts and conforms to the
FullyNamed protocol:
Method Requirements
Protocols can require specific instance methods and type methods to
be implemented by conforming types. These methods are written as
part of the protocol’s definition in exactly the same way as for normal
1 protocol SomeProtocol {
2 static func someTypeMethod()
3 }
1 protocol RandomNumberGenerator {
2 func random() -> Double
3 }
1 class LinearCongruentialGenerator:
RandomNumberGenerator {
2 var lastRandom = 42.0
3 let m = 139968.0
4 let a = 3877.0
5 let c = 29573.0
6 func random() -> Double {
7 lastRandom = ((lastRandom * a + c)
8 .truncatingRemainder(dividingBy:m))
9 return lastRandom / m
10 }
11 }
12 let generator = LinearCongruentialGenerator()
13 print("Here's a random number: \
(generator.random())")
14 // Prints "Here's a random number:
0.3746499199817101"
15 print("And another one: \(generator.random())")
16 // Prints "And another one: 0.729023776863283"
NOTE
1 protocol SomeProtocol {
2 init(someParameter: Int)
3 }
The use of the required modifier ensures that you provide an explicit
or inherited implementation of the initializer requirement on all
subclasses of the conforming class, such that they also conform to
the protocol.
You don’t need to mark protocol initializer implementations with the required
modifier on classes that are marked with the final modifier, because final
classes can’t subclassed. For more about the final modifier, see Preventing
Overrides.
1 protocol SomeProtocol {
2 init()
3 }
4
5 class SomeSuperClass {
6 init() {
7 // initializer implementation goes here
8 }
9 }
10
11 class SomeSubClass: SomeSuperClass, SomeProtocol {
12 // "required" from SomeProtocol conformance;
"override" from SomeSuperClass
13 required override init() {
14 // initializer implementation goes here
15 }
16 }
Protocols as Types
Protocols don’t actually implement any functionality themselves.
Nonetheless, you can use protocols as a fully fledged types in your
code. Using a protocol as a type is sometimes called an existential
type, which comes from the phrase “there exists a type T such that T
conforms to the protocol”.
You can use a protocol in many places where other types are
allowed, including:
NOTE
Because protocols are types, begin their names with a capital letter (such as
FullyNamed and RandomNumberGenerator) to match the names of other
types in Swift (such as Int, String, and Double).
Dice also has an initializer, to set up its initial state. This initializer has
a parameter called generator, which is also of type
RandomNumberGenerator. You can pass a value of any conforming
type in to this parameter when initializing a new Dice instance.
Here’s how the Dice class can be used to create a six-sided dice with
a LinearCongruentialGenerator instance as its random number
generator:
The example below defines two protocols for use with dice-based
board games:
1 protocol DiceGame {
2 var dice: Dice { get }
3 func play()
4 }
5 protocol DiceGameDelegate: AnyObject {
6 func gameDidStart(_ game: DiceGame)
7 func game(_ game: DiceGame,
didStartNewTurnWithDiceRoll diceRoll: Int)
8 func gameDidEnd(_ game: DiceGame)
9 }
The Snakes and Ladders game board setup takes place within the
class’s init() initializer. All game logic is moved into the protocol’s
play method, which uses the protocol’s required dice property to
provide its dice roll values.
NOTE
1 protocol TextRepresentable {
2 var textualDescription: String { get }
3 }
The Dice class from above can be extended to adopt and conform to
TextRepresentable:
NOTE
It’s now possible to iterate over the items in the array, and print each
item’s textual description:
Protocol Inheritance
A protocol can inherit one or more other protocols and can add
further requirements on top of the requirements it inherits. The syntax
for protocol inheritance is similar to the syntax for class inheritance,
If the square’s value is less than 0, it’s the head of a snake, and
is represented by ▼.
1 print(game.prettyTextualDescription)
2 // A game of Snakes and Ladders with 25 squares:
3 // ○ ○ ▲ ○ ○ ▲ ○ ○ ▲ ▲ ○ ○ ○ ▼ ○ ○ ○ ○ ▼ ○ ○ ▼ ○ ▼ ○
Class-Only Protocols
You can limit protocol adoption to class types (and not structures or
enumerations) by adding the AnyObject protocol to a protocol’s
inheritance list.
Protocol Composition
It can be useful to require a type to conform to multiple protocols at
the same time. You can combine multiple protocols into a single
requirement with a protocol composition. Protocol compositions
behave as if you defined a temporary local protocol that has the
combined requirements of all protocols in the composition. Protocol
compositions don’t define any new protocol types.
Here are two classes, Circle and Country, both of which conform to
the HasArea protocol:
The Circle, Country and Animal classes don’t have a shared base
class. Nonetheless, they’re all classes, and so instances of all three
types can be used to initialize an array that stores values of type
AnyObject:
The objects array can now be iterated, and each object in the array
can be checked to see if it conforms to the HasArea protocol:
NOTE
1 class Counter {
2 var count = 0
3 var dataSource: CounterDataSource?
4 func increment() {
5 if let amount = dataSource?.increment?
(forCount: count) {
6 count += amount
7 } else if let amount =
dataSource?.fixedIncrement {
8 count += amount
9 }
10 }
11 }
Note that two levels of optional chaining are at play here. First, it’s
possible that dataSource may be nil, and so dataSource has a
question mark after its name to indicate that increment(forCount:)
should be called only if dataSource isn’t nil. Second, even if
dataSource does exist, there’s no guarantee that it implements
increment(forCount:), because it’s an optional requirement. Here,
the possibility that increment(forCount:) might not be implemented
is also handled by optional chaining. The call to
increment(forCount:) happens only if increment(forCount:) exists
—that is, if it isn’t nil. This is why increment(forCount:) is also
written with a question mark after its name.
You can use an instance of ThreeSource as the data source for a new
Counter instance:
Protocol Extensions
Protocols can be extended to provide method, initializer, subscript,
and computed property implementations to conforming types. This
allows you to define behavior on protocols themselves, rather than in
each type’s individual conformance or in a global function.
NOTE
1 extension PrettyTextRepresentable {
2 var prettyTextualDescription: String {
3 return textualDescription
4 }
5 }
The allEqual() method returns true only if all the elements in the
collection are equal.
Consider two arrays of integers, one where all the elements are the
same, and one where they aren’t:
NOTE
Generics are one of the most powerful features of Swift, and much of
the Swift standard library is built with generic code. In fact, you’ve
been using generics throughout the Language Guide, even if you
didn’t realize it. For example, Swift’s Array and Dictionary types are
both generic collections. You can create an array that holds Int
values, or an array that holds String values, or indeed an array for
any other type that can be created in Swift. Similarly, you can create a
dictionary to store values of any specified type, and there are no
limitations on what that type can be.
1 var someInt = 3
2 var anotherInt = 107
3 swapTwoInts(&someInt, &anotherInt)
4 print("someInt is now \(someInt), and anotherInt is
now \(anotherInt)")
5 // Prints "someInt is now 107, and anotherInt is now
3"
NOTE
In all three functions, the types of a and b must be the same. If a and b aren’t of
the same type, it isn’t possible to swap their values. Swift is a type-safe
language, and doesn’t allow (for example) a variable of type String and a
variable of type Double to swap values with each other. Attempting to do so
results in a compile-time error.
1 var someInt = 3
2 var anotherInt = 107
3 swapTwoValues(&someInt, &anotherInt)
4 // someInt is now 107, and anotherInt is now 3
5
6 var someString = "hello"
7 var anotherString = "world"
8 swapTwoValues(&someString, &anotherString)
9 // someString is now "world", and anotherString is
now "hello"
NOTE
Type Parameters
Once you specify a type parameter, you can use it to define the type of
a function’s parameters (such as the a and b parameters of the
swapTwoValues(_:_:) function), or as the function’s return type, or as
a type annotation within the body of the function. In each case, the
type parameter is replaced with an actual type whenever the function
is called. (In the swapTwoValues(_:_:) example above, T was replaced
with Int the first time the function was called, and was replaced with
String the second time it was called.)
You can provide more than one type parameter by writing multiple
type parameter names within the angle brackets, separated by
commas.
NOTE
Always give type parameters upper camel case names (such as T and
MyTypeParameter) to indicate that they’re a placeholder for a type, not a value.
This section shows you how to write a generic collection type called
Stack. A stack is an ordered set of values, similar to an array, but with
a more restricted set of operations than Swift’s Array type. An array
allows new items to be inserted and removed at any location in the
array. A stack, however, allows new items to be appended only to the
end of the collection (known as pushing a new value on to the stack).
Similarly, a stack allows items to be removed only from the end of the
collection (known as popping a value off the stack).
NOTE
The illustration below shows the push and pop behavior for a stack:
3. The stack now holds four values, with the most recent one at the
top.
5. After popping a value, the stack once again holds three values.
This structure uses an Array property called items to store the values
in the stack. Stack provides two methods, push and pop, to push and
pop values on and off the stack. These methods are marked as
mutating, because they need to modify (or mutate) the structure’s
items array.
The IntStack type shown above can only be used with Int values,
however. It would be much more useful to define a generic Stack
structure, that can manage a stack of any type of value.
Note how the generic version of Stack is essentially the same as the
nongeneric version, but with a type parameter called Element instead
of an actual type of Int. This type parameter is written within a pair of
angle brackets (<Element>) immediately after the structure’s name.
Popping a value from the stack removes and returns the top value,
"cuatro":
Here’s how the stack looks after popping its top value:
The following example extends the generic Stack type to add a read-
only computed property called topItem, which returns the top item on
the stack without popping it from the stack:
1 extension Stack {
2 var topItem: Element? {
3 return items.isEmpty ? nil :
items[items.count - 1]
4 }
5 }
Note that this extension doesn’t define a type parameter list. Instead,
the Stack type’s existing type parameter name, Element, is used within
the extension to indicate the optional type of the topItem computed
property.
The topItem computed property can now be used with any Stack
instance to access and query its top item without removing it.
Type Constraints
The swapTwoValues(_:_:) function and the Stack type can work with
any type. However, it’s sometimes useful to enforce certain type
constraints on the types that can be used with generic functions and
generic types. Type constraints specify that a type parameter must
inherit from a specific class, or conform to a particular protocol or
protocol composition.
You can define your own type constraints when creating custom
generic types, and these constraints provide much of the power of
generic programming. Abstract concepts like Hashable characterize
types in terms of their conceptual characteristics, rather than their
concrete type.
The hypothetical function above has two type parameters. The first
type parameter, T, has a type constraint that requires T to be a
subclass of SomeClass. The second type parameter, U, has a type
constraint that requires U to conform to the protocol SomeProtocol.
The principle of finding the index of a value in an array isn’t useful only
for strings, however. You can write the same functionality as a generic
function by replacing any mention of strings with values of some type
T instead.
All is not lost, however. The Swift standard library defines a protocol
called Equatable, which requires any conforming type to implement
the equal to operator (==) and the not equal to operator (!=) to
compare any two values of that type. All of Swift’s standard types
automatically support the Equatable protocol.
Associated Types
When defining a protocol, it’s sometimes useful to declare one or
more associated types as part of the protocol’s definition. An
associated type gives a placeholder name to a type that’s used as part
of the protocol. The actual type to use for that associated type isn’t
specified until the protocol is adopted. Associated types are specified
with the associatedtype keyword.
This protocol doesn’t specify how the items in the container should be
stored or what type they’re allowed to be. The protocol only specifies
the three bits of functionality that any type must provide in order to be
considered a Container. A conforming type can provide additional
functionality, as long as it satisfies these three requirements.
You can also make the generic Stack type conform to the Container
protocol:
This time, the type parameter Element is used as the type of the
append(_:) method’s item parameter and the return type of the
subscript. Swift can therefore infer that Element is the appropriate type
to use as the Item for this particular container.
1 protocol Container {
2 associatedtype Item: Equatable
3 mutating func append(_ item: Item)
4 var count: Int { get }
5 subscript(i: Int) -> Item { get }
6 }
In this protocol, Suffix is an associated type, like the Item type in the
Container example above. Suffix has two constraints: It must
conform to the SuffixableContainer protocol (the protocol currently
being defined), and its Item type must be the same as the container’s
Item type. The constraint on Item is a generic where clause, which is
discussed in Associated Types with a Generic Where Clause below.
Here’s an extension of the Stack type from Generic Types above that
adds conformance to the SuffixableContainer protocol:
In the example above, the Suffix associated type for Stack is also
Stack, so the suffix operation on Stack returns another Stack.
Alternatively, a type that conforms to SuffixableContainer can have a
Suffix type that’s different from itself—meaning the suffix operation
can return a different type. For example, here’s an extension to the
nongeneric IntStack type that adds SuffixableContainer
conformance, using Stack<Int> as its suffix type instead of IntStack:
The Item for C1 must be the same as the Item for C2 (written as
C1.Item == C2.Item).
The first and second requirements are defined in the function’s type
parameter list, and the third and fourth requirements are defined in the
function’s generic where clause.
The third and fourth requirements combine to mean that the items in
anotherContainer can also be checked with the != operator, because
they’re exactly the same type as the items in someContainer.
After making this check, the function iterates over all of the items in
someContainer with a for-in loop and the half-open range operator
(..<). For each item, the function checks whether the item from
someContainer isn’t equal to the corresponding item in
anotherContainer. If the two items aren’t equal, then the two
containers don’t match, and the function returns false.
This new isTop(_:) method first checks that the stack isn’t empty, and
then compares the given item against the stack’s topmost item. If you
tried to do this without a generic where clause, you would have a
problem: The implementation of isTop(_:) uses the == operator, but
the definition of Stack doesn’t require its items to be equatable, so
using the == operator results in a compile-time error. Using a generic
where clause lets you add a new requirement to the extension, so that
the extension adds the isTop(_:) method only when the items in the
stack are equatable.
1 if stackOfStrings.isTop("tres") {
2 print("Top element is tres.")
3 } else {
4 print("Top element is something else.")
5 }
6 // Prints "Top element is tres."
1 struct NotEquatable { }
2 var notEquatableStack = Stack<NotEquatable>()
3 let notEquatableValue = NotEquatable()
4 notEquatableStack.push(notEquatableValue)
5 notEquatableStack.isTop(notEquatableValue) // Error
You can use a generic where clause with extensions to a protocol. The
example below extends the Container protocol from the previous
examples to add a startsWith(_:) method.
The startsWith(_:) method first makes sure that the container has at
least one item, and then it checks whether the first item in the
container matches the given item. This new startsWith(_:) method
can be used with any type that conforms to the Container protocol,
including the stacks and arrays used above, as long as the container’s
items are equatable.
If you want to write this code without using contextual where clauses,
you write two extensions, one for each generic where clause. The
example above and the example below have the same behavior.
In the version of this example that uses contextual where clauses, the
implementation of average() and endsWith(_:) are both in the same
extension because each method’s generic where clause states the
requirements that need to be satisfied to make that method available.
Moving those requirements to the extensions’ generic where clauses
makes the methods available in the same situations, but requires one
extension per requirement.
1 protocol Container {
2 associatedtype Item
3 mutating func append(_ item: Item)
4 var count: Int { get }
5 subscript(i: Int) -> Item { get }
6
7 associatedtype Iterator: IteratorProtocol where
Iterator.Element == Item
8 func makeIterator() -> Iterator
9 }
The generic where clause on Iterator requires that the iterator must
traverse over elements of the same item type as the container’s items,
regardless of the iterator’s type. The makeIterator() function
provides access to a container’s iterator.
For a protocol that inherits from another protocol, you add a constraint
to an inherited associated type by including the generic where clause
in the protocol declaration. For example, the following code declares a
ComparableContainer protocol that requires Item to conform to
Comparable:
1 extension Container {
2 subscript<Indices: Sequence>(indices: Indices) ->
[Item]
3 where Indices.Iterator.Element == Int {
4 var result: [Item] = []
5 for index in indices {
6 result.append(self[index])
7 }
8 return result
9 }
10 }
The generic where clause requires that the iterator for the
sequence must traverse over elements of type Int. This ensures
Taken together, these constraints mean that the value passed for the
indices parameter is a sequence of integers.
The code that calls max(_:_:) chooses the values for x and y, and the
type of those values determines the concrete type of T. The calling
code can use any type that conforms to the Comparable protocol. The
code inside the function is written in a general way so it can handle
whatever type the caller provides. The implementation of max(_:_:)
uses only functionality that all Comparable types share.
Those roles are reversed for a function with an opaque return type.
An opaque type lets the function implementation pick the type for the
value it returns in a way that’s abstracted away from the code that
calls the function. For example, the function in the following example
returns a trapezoid without exposing the underlying type of that
shape.
This example highlights the way that an opaque return type is like the
reverse of a generic type. The code inside makeTrapezoid() can
return any type it needs to, as long as that type conforms to the Shape
protocol, like the calling code does for a generic function. The code
that calls the function needs to be written in a general way, like the
implementation of a generic function, so that it can work with any
Shape value that’s returned by makeTrapezoid().
You can also combine opaque return types with generics. The
functions in the following code both return a value of some type that
conforms to the Shape protocol.
In this case, the underlying type of the return value varies depending
on T: Whatever shape is passed it, repeat(shape:count:) creates
and returns an array of that shape. Nevertheless, the return value
always has the same underlying type of [T], so it follows the
requirement that functions with opaque return types must return
values of only a single type.
The error on the last line of the example occurs for several reasons.
The immediate issue is that the Shape doesn’t include an == operator
as part of its protocol requirements. If you try adding one, the next
issue you’ll encounter is that the == operator needs to know the types
of its left-hand and right-hand arguments. This sort of operator
usually takes arguments of type Self, matching whatever concrete
type adopts the protocol, but adding a Self requirement to the
protocol doesn’t allow for the type erasure that happens when you
use the protocol as a type.
1 protocol Container {
2 associatedtype Item
3 var count: Int { get }
4 subscript(i: Int) -> Item { get }
5 }
6 extension Array: Container { }
You can’t use Container as the return type of a function because that
protocol has an associated type. You also can’t use it as constraint in
To make sure that instances don’t disappear while they’re still needed,
ARC tracks how many properties, constants, and variables are
currently referring to each class instance. ARC will not deallocate an
instance as long as at least one active reference to that instance still
exists.
ARC in Action
Here’s an example of how Automatic Reference Counting works. This
example starts with a simple class called Person, which defines a
stored constant property called name:
The Person class has an initializer that sets the instance’s name
property and prints a message to indicate that initialization is
underway. The Person class also has a deinitializer that prints a
message when an instance of the class is deallocated.
The next code snippet defines three variables of type Person?, which
are used to set up multiple references to a new Person instance in
subsequent code snippets. Because these variables are of an optional
type (Person?, not Person), they’re automatically initialized with a
value of nil, and don’t currently reference a Person instance.
You can now create a new Person instance and assign it to one of
these three variables:
If you assign the same Person instance to two more variables, two
more strong references to that instance are established:
1 reference2 = reference1
2 reference3 = reference1
There are now three strong references to this single Person instance.
1 reference1 = nil
2 reference2 = nil
ARC doesn’t deallocate the Person instance until the third and final
strong reference is broken, at which point it’s clear that you are no
longer using the Person instance:
Both of these classes also define a deinitializer, which prints the fact
that an instance of that class is being deinitialized. This enables you to
see whether instances of Person and Apartment are being deallocated
as expected.
Here’s how the strong references look after creating and assigning
these two instances. The john variable now has a strong reference to
the new Person instance, and the unit4A variable has a strong
reference to the new Apartment instance:
You can now link the two instances together so that the person has an
apartment, and the apartment has a tenant. Note that an exclamation
point (!) is used to unwrap and access the instances stored inside the
john and unit4A optional variables, so that the properties of those
instances can be set:
Here’s how the strong references look after you link the two instances
together:
1 john = nil
2 unit4A = nil
Note that neither deinitializer was called when you set these two
variables to nil. The strong reference cycle prevents the Person and
Apartment instances from ever being deallocated, causing a memory
leak in your app.
Here’s how the strong references look after you set the john and
unit4A variables to nil:
Use a weak reference when the other instance has a shorter lifetime—
that is, when the other instance can be deallocated first. In the
Apartment example above, it’s appropriate for an apartment to be able
to have no tenant at some point in its lifetime, and so a weak reference
is an appropriate way to break the reference cycle in this case. In
contrast, use an unowned reference when the other instance has the
same lifetime or a longer lifetime.
You can check for the existence of a value in the weak reference, just
like any other optional value, and you will never end up with a
reference to an invalid instance that no longer exists.
NOTE
Property observers aren’t called when ARC sets a weak reference to nil.
The strong references from the two variables (john and unit4A) and
the links between the two instances are created as before:
1 john = nil
2 // Prints "John Appleseed is being deinitialized"
NOTE
In systems that use garbage collection, weak pointers are sometimes used to
implement a simple caching mechanism because objects with no strong
references are deallocated only when memory pressure triggers garbage
collection. However, with ARC, values are deallocated as soon as their last
strong reference is removed, making weak references unsuitable for such a
purpose.
Unowned References
Like a weak reference, an unowned reference doesn’t keep a strong
hold on the instance it refers to. Unlike a weak reference, however, an
unowned reference is used when the other instance has the same
lifetime or a longer lifetime. You indicate an unowned reference by
placing the unowned keyword before a property or variable declaration.
Use an unowned reference only when you are sure that the reference always
refers to an instance that hasn’t been deallocated.
If you try to access the value of an unowned reference after that instance has
been deallocated, you’ll get a runtime error.
Because a credit card will always have a customer, you define its
customer property as an unowned reference, to avoid a strong
reference cycle:
NOTE
The number property of the CreditCard class is defined with a type of UInt64
rather than Int, to ensure that the number property’s capacity is large enough
to store a 16-digit card number on both 32-bit and 64-bit systems.
You can now create a Customer instance, and use it to initialize and
assign a new CreditCard instance as that customer’s card property:
Here’s how the references look, now that you’ve linked the two
instances:
1 john = nil
2 // Prints "John Appleseed is being deinitialized"
3 // Prints "Card #1234567890123456 is being
deinitialized"
The final code snippet above shows that the deinitializers for the
Customer instance and CreditCard instance both print their
“deinitialized” messages after the john variable is set to nil.
NOTE
The examples above show how to use safe unowned references. Swift also
provides unsafe unowned references for cases where you need to disable
runtime safety checks—for example, for performance reasons. As with all
unsafe operations, you take on the responsibility for checking that code for
safety.
You indicate an unsafe unowned reference by writing unowned(unsafe). If you
try to access an unsafe unowned reference after the instance that it refers to is
deallocated, your program will try to access the memory location where the
instance used to be, which is an unsafe operation.
The code above creates a department and its three courses. The intro
and intermediate courses both have a suggested next course stored
in their nextCourse property, which maintains an unowned optional
reference to the course a student should take after completing this
one.
1 class Country {
2 let name: String
3 var capitalCity: City!
4 init(name: String, capitalName: String) {
5 self.name = name
6 self.capitalCity = City(name: capitalName,
country: self)
7 }
8 }
9
10 class City {
11 let name: String
12 unowned let country: Country
13 init(name: String, country: Country) {
14 self.name = name
15 self.country = country
16 }
17 }
All of this means that you can create the Country and City instances
in a single statement, without creating a strong reference cycle, and
the capitalCity property can be accessed directly, without needing to
use an exclamation point to unwrap its optional value:
This strong reference cycle occurs because closures, like classes, are
reference types. When you assign a closure to a property, you are
assigning a reference to that closure. In essence, it’s the same
problem as above—two strong references are keeping each other
alive. However, rather than two class instances, this time it’s a class
instance and a closure that are keeping each other alive.
The example below shows how you can create a strong reference
cycle when using a closure that references self. This example defines
1 class HTMLElement {
2
3 let name: String
4 let text: String?
5
6 lazy var asHTML: () -> String = {
7 if let text = self.text {
8 return "<\(self.name)>\(text)</\
(self.name)>"
9 } else {
10 return "<\(self.name) />"
11 }
12 }
13
14 init(name: String, text: String? = nil) {
15 self.name = name
16 self.text = text
17 }
18
19 deinit {
20 print("\(name) is being deinitialized")
21 }
22
23 }
NOTE
The asHTML property is declared as a lazy property, because it’s only needed if
and when the element actually needs to be rendered as a string value for some
HTML output target. The fact that asHTML is a lazy property means that you can
refer to self within the default closure, because the lazy property will not be
accessed until after initialization has been completed and self is known to
exist.
Here’s how you use the HTMLElement class to create and print a new
instance:
NOTE
Even though the closure refers to self multiple times, it only captures one
strong reference to the HTMLElement instance.
If you set the paragraph variable to nil and break its strong reference
to the HTMLElement instance, neither the HTMLElement instance nor its
closure are deallocated, because of the strong reference cycle:
NOTE
Place the capture list before a closure’s parameter list and return type
if they’re provided:
NOTE
If the captured reference will never become nil, it should always be captured
as an unowned reference, rather than a weak reference.
Here’s how the references look with the capture list in place:
1 paragraph = nil
2 // Prints "p is being deinitialized"
Swift also makes sure that multiple accesses to the same area of
memory don’t conflict, by requiring code that modifies a location in
memory to have exclusive access to that memory. Because Swift
manages memory automatically, most of the time you don’t have to
think about accessing memory at all. However, it’s important to
understand where potential conflicts can occur, so you can avoid
writing code that has conflicting access to memory. If your code does
contain conflicts, you’ll get a compile-time or runtime error.
You can see a similar problem by thinking about how you update a
budget that’s written on a piece of paper. Updating the budget is a
two-step process: First you add the items’ names and prices, and
then you change the total amount to reflect the items currently on the
list. Before and after the update, you can read any information from
the budget and get a correct answer, as shown in the figure below.
NOTE
1 var stepSize = 1
2
3 func increment(_ number: inout Int) {
4 number += stepSize
5 }
6
7 increment(&stepSize)
8 // Error: conflicting accesses to stepSize
NOTE
Because operators are functions, they can also have long-term accesses to
their in-out parameters. For example, if balance(_:_:) was an operator
function named <^>, writing playerOneScore <^> playerOneScore would
result in the same conflict as balance(&playerOneScore,
&playerOneScore).
The mutating method needs write access to self for the duration of
the method, and the in-out parameter needs write access to teammate
for the same duration. Within the method, both self and teammate
refer to the same location in memory—as shown in the figure below.
The two write accesses refer to the same memory and they overlap,
producing a conflict.
The code below shows that the same error appears for overlapping
write accesses to the properties of a structure that’s stored in a global
variable.
In the example above, Oscar’s health and energy are passed as the
two in-out parameters to balance(_:_:). The compiler can prove that
memory safety is preserved because the two stored properties don’t
interact in any way.
If the compiler can’t prove the access is safe, it doesn’t allow the
access.
NOTE
The various aspects of your code that can have access control applied to
them (properties, types, functions, and so on) are referred to as “entities” in
the sections below, for brevity.
A source file is a single Swift source code file within a module (in
effect, a single file within an app or framework). Although it’s common
to define individual types in separate source files, a single source file
can contain definitions for multiple types, functions, and so on.
Access Levels
Swift provides five different access levels for entities within your code.
These access levels are relative to the source file in which an entity is
defined, and also relative to the module that source file belongs to.
Open access is the highest (least restrictive) access level and private
access is the lowest (most restrictive) access level.
For example:
Any internal implementation details of your framework can still use the default
access level of internal, or can be marked as private or file private if you want
to hide them from other parts of the framework’s internal code. You need to
mark an entity as open or public only if you want it to become part of your
framework’s API.
1 class SomeInternalClass {} //
implicitly internal
2 let someInternalConstant = 0 //
implicitly internal
Custom Types
If you want to specify an explicit access level for a custom type, do so
at the point that you define the type. The new type can then be used
wherever its access level permits. For example, if you define a file-
private class, that class can only be used as the type of a property, or
The access control level of a type also affects the default access level
of that type’s members (its properties, methods, initializers, and
subscripts). If you define a type’s access level as private or file
private, the default access level of its members will also be private or
file private. If you define a type’s access level as internal or public (or
use the default access level of internal without specifying an access
level explicitly), the default access level of the type’s members will be
internal.
I M P O R TA N T
A public type defaults to having internal members, not public members. If you
want a type member to be public, you must explicitly mark it as such. This
requirement ensures that the public-facing API for a type is something you opt
in to publishing, and avoids presenting the internal workings of a type as
public API by mistake.
Tuple Types
The access level for a tuple type is the most restrictive access level of
all types used in that tuple. For example, if you compose a tuple from
two different types, one with internal access and one with private
access, the access level for that compound tuple type will be private.
NOTE
Tuple types don’t have a standalone definition in the way that classes,
structures, enumerations, and functions do. A tuple type’s access level is
determined automatically from the types that make up the tuple type, and
can’t be specified explicitly.
Function Types
The access level for a function type is calculated as the most
restrictive access level of the function’s parameter types and return
type. You must specify the access level explicitly as part of the
function’s definition if the function’s calculated access level doesn’t
match the contextual default.
The function’s return type is a tuple type composed from two of the
custom classes defined above in Custom Types. One of these
classes is defined as internal, and the other is defined as private.
Therefore, the overall access level of the compound tuple type is
private (the minimum access level of the tuple’s constituent types).
Because the function’s return type is private, you must mark the
function’s overall access level with the private modifier for the
function declaration to be valid:
It’s not valid to mark the definition of someFunction() with the public
or internal modifiers, or to use the default setting of internal,
because public or internal users of the function might not have
appropriate access to the private class used in the function’s return
type.
Nested Types
The access level of a nested type is the same as its containing type,
unless the containing type is public. Nested types defined within a
public type have an automatic access level of internal. If you want a
nested type within a public type to be publicly available, you must
explicitly declare the nested type as public.
In addition, for classes that are defined in the same module, you can
override any class member (method, property, initializer, or subscript)
that’s visible in a certain access context. For classes that are defined
in another module, you can override any open class member.
1 public class A {
2 fileprivate func someMethod() {}
3 }
4
5 internal class B: A {
6 override internal func someMethod() {}
7 }
1 public class A {
2 fileprivate func someMethod() {}
3 }
4
5 internal class B: A {
6 override internal func someMethod() {
7 super.someMethod()
8 }
9 }
You can give a setter a lower access level than its corresponding
getter, to restrict the read-write scope of that variable, property, or
subscript. You assign a lower access level by writing
fileprivate(set), private(set), or internal(set) before the var or
subscript introducer.
NOTE
Note that you can assign an explicit access level for both a getter and
a setter if required. The example below shows a version of the
TrackedString structure in which the structure is defined with an
explicit access level of public. The structure’s members (including the
numberOfEdits property) therefore have an internal access level by
default. You can make the structure’s numberOfEdits property getter
public, and its property setter private, by combining the public and
private(set) access-level modifiers:
Initializers
Custom initializers can be assigned an access level less than or
equal to the type that they initialize. The only exception is for required
initializers (as defined in Required Initializers). A required initializer
must have the same access level as the class it belongs to.
Default Initializers
As described in Default Initializers, Swift automatically provides a
default initializer without any arguments for any structure or base
class that provides default values for all of its properties and doesn’t
provide at least one initializer itself.
As with the default initializer above, if you want a public structure type
to be initializable with a memberwise initializer when used in another
module, you must provide a public memberwise initializer yourself as
part of the type’s definition.
Protocols
If you want to assign an explicit access level to a protocol type, do so
at the point that you define the protocol. This enables you to create
protocols that can only be adopted within a certain access context.
Protocol Inheritance
If you define a new protocol that inherits from an existing protocol, the
new protocol can have at most the same access level as the protocol
it inherits from. For example, you can’t write a public protocol that
inherits from an internal protocol.
Protocol Conformance
A type can conform to a protocol with a lower access level than the
type itself. For example, you can define a public type that can be
used in other modules, but whose conformance to an internal
protocol can only be used within the internal protocol’s defining
module.
Extensions
You can extend a class, structure, or enumeration in any access
context in which the class, structure, or enumeration is available. Any
type members added in an extension have the same default access
level as type members declared in the original type being extended. If
you extend a public or internal type, any new type members you add
have a default access level of internal. If you extend a file-private
type, any new type members you add have a default access level of
file private. If you extend a private type, any new type members you
add have a default access level of private.
This behavior means you can use extensions in the same way to
organize your code, whether or not your types have private entities.
For example, given the following simple protocol:
1 protocol SomeProtocol {
2 func doSomething()
3 }
1 struct SomeStruct {
2 private var privateVariable = 12
3 }
4
5 extension SomeStruct: SomeProtocol {
6 func doSomething() {
7 print(privateVariable)
8 }
9 }
Type Aliases
Any type aliases you define are treated as distinct types for the
purposes of access control. A type alias can have an access level
less than or equal to the access level of the type it aliases. For
example, a private type alias can alias a private, file-private, internal,
public, or open type, but a public type alias can’t alias an internal, file-
private, or private type.
NOTE
This rule also applies to type aliases for associated types used to satisfy
protocol conformances.
You’re not limited to the predefined operators. Swift gives you the
freedom to define your own custom infix, prefix, postfix, and
assignment operators, with custom precedence and associativity
values. These operators can be used and adopted in your code like
any of the predefined operators, and you can even extend existing
types to support the custom operators you define.
Bitwise Operators
Bitwise operators enable you to manipulate the individual raw data
bits within a data structure. They’re often used in low-level
programming, such as graphics programming and device driver
UInt8 integers have eight bits and can store any value between 0 and
255. This example initializes a UInt8 integer with the binary value
00001111, which has its first four bits set to 0, and its second four bits
set to 1. This is equivalent to a decimal value of 15.
Bitwise OR Operator
The bitwise OR operator (|) compares the bits of two numbers. The
operator returns a new number whose bits are set to 1 if the bits are
equal to 1 in either input number:
Bitwise left and right shifts have the effect of multiplying or dividing an
integer by a factor of two. Shifting an integer’s bits to the left by one
position doubles its value, whereas shifting it to the right by one
position halves its value.
2. Any bits that are moved beyond the bounds of the integer’s
storage are discarded.
3. Zeros are inserted in the spaces left behind after the original bits
are moved to the left or right.
You can use bit shifting to encode and decode values within other
data types:
This number is then shifted 16 places to the right (>> 16). Each pair of
characters in a hexadecimal number uses 8 bits, so a move 16 places
to the right will convert 0xCC0000 into 0x0000CC. This is the same as
0xCC, which has a decimal value of 204.
The shifting behavior is more complex for signed integers than for
unsigned integers, because of the way signed integers are
represented in binary. (The examples below are based on 8-bit
signed integers for simplicity, but the same principles apply for signed
integers of any size.)
Signed integers use their first bit (known as the sign bit) to indicate
whether the integer is positive or negative. A sign bit of 0 means
positive, and a sign bit of 1 means negative.
The remaining bits (known as the value bits) store the actual value.
Positive numbers are stored in exactly the same way as for unsigned
integers, counting upwards from 0. Here’s how the bits inside an Int8
look for the number 4:
The sign bit is 0 (meaning “positive”), and the seven value bits are
just the number 4, written in binary notation.
Here’s how the bits inside an Int8 look for the number -4:
Second, the two’s complement representation also lets you shift the
bits of negative numbers to the left and right like positive numbers,
and still end up doubling them for every shift you make to the left, or
halving them for every shift you make to the right. To achieve this, an
extra rule is used when signed integers are shifted to the right: When
you shift signed integers to the right, apply the same rules as for
unsigned integers, but fill any empty bits on the left with the sign bit,
rather than with a zero.
Because of the special way that positive and negative numbers are
stored, shifting either of them to the right moves them closer to zero.
Keeping the sign bit the same during this shift means that negative
integers remain negative as their value moves closer to zero.
Overflow Operators
If you try to insert a number into an integer constant or variable that
can’t hold that value, by default Swift reports an error rather than
allowing an invalid value to be created. This behavior gives extra
safety when you work with numbers that are too large or too small.
For example, the Int16 integer type can hold any signed integer
between -32768 and 32767. Trying to set an Int16 constant or
variable to a number outside of this range causes an error:
Value Overflow
Numbers can overflow in both the positive and negative direction.
Overflow also occurs for signed integers. All addition and subtraction
for signed integers is performed in bitwise fashion, with the sign bit
1 2 + 3 % 4 * 5
2 // this equals 17
If you read strictly from left to right, you might expect the expression
to be calculated as follows:
2 plus 3 equals 5
5 remainder 4 equals 1
1 times 5 equals 5
2 + ((3 % 4) * 5)
2 + (3 * 5)
2 + 15
NOTE
Swift’s operator precedences and associativity rules are simpler and more
predictable than those found in C and Objective-C. However, this means that
they aren’t exactly the same as in C-based languages. Be careful to ensure
that operator interactions still behave in the way you intend when porting
existing code to Swift.
Operator Methods
Classes and structures can provide their own implementations of
existing operators. This is known as overloading the existing
operators.
1 struct Vector2D {
2 var x = 0.0, y = 0.0
3 }
4
5 extension Vector2D {
6 static func + (left: Vector2D, right: Vector2D)
-> Vector2D {
7 return Vector2D(x: left.x + right.x, y:
left.y + right.y)
8 }
9 }
This example adds together the vectors (3.0, 1.0) and (2.0, 4.0)
to make the vector (5.0, 5.0), as illustrated below.
The example above implements the unary minus operator (-a) for
Vector2D instances. The unary minus operator is a prefix operator,
and so this method has to be qualified with the prefix modifier.
1 extension Vector2D {
2 static func += (left: inout Vector2D, right:
Vector2D) {
3 left = left + right
4 }
5 }
NOTE
It isn’t possible to overload the default assignment operator (=). Only the
compound assignment operators can be overloaded. Similarly, the ternary
conditional operator (a ? b : c) can’t be overloaded.
Equivalence Operators
You can now use this operator to check whether two Vector2D
instances are equivalent:
Custom Operators
You can declare and implement your own custom operators in
addition to the standard operators provided by Swift. For a list of
characters that can be used to define custom operators, see
Operators.
The example above defines a new prefix operator called +++. This
operator doesn’t have an existing meaning in Swift, and so it’s given
its own custom meaning below in the specific context of working with
Vector2D instances. For the purposes of this example, +++ is treated
as a new “prefix doubling” operator. It doubles the x and y values of a
Vector2D instance, by adding the vector to itself with the addition
1 extension Vector2D {
2 static prefix func +++ (vector: inout Vector2D)
-> Vector2D {
3 vector += vector
4 return vector
5 }
6 }
7
8 var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
9 let afterDoubling = +++toBeDoubled
10 // toBeDoubled now has values of (2.0, 8.0)
11 // afterDoubling also has values of (2.0, 8.0)
Result Builders
A result builder is a type you define that adds syntax for creating
nested data, like a list or tree, in a natural, declarative way. The code
that uses the result builder can include ordinary Swift syntax, like if
and for, to handle conditional or repeated pieces of data.
The code below defines a few types for drawing on a single line using
stars and text.
This code works, but it’s a little awkward. The deeply nested
parentheses after AllCaps are hard to read. The fallback logic to use
“World” when name is nil has to be done inline using the ?? operator,
1 @resultBuilder
2 struct DrawingBuilder {
3 static func buildBlock(_ components:
Drawable...) -> Drawable {
4 return Line(elements: components)
5 }
6 static func buildEither(first: Drawable) ->
Drawable {
7 return first
8 }
9 static func buildEither(second: Drawable) ->
Drawable {
10 return second
11 }
12 }
To add support for writing for loops in the special drawing syntax,
add a buildArray(_:) method.
In the code above, the for loop creates an array of drawings, and the
buildArray(_:) method turns that array into a Line.
For a complete list of how Swift transforms builder syntax into calls to
the builder type’s methods, see resultBuilder.
This part of the book describes the formal grammar of the Swift
programming language. The grammar described here is intended to
help you understand the language in more detail, rather than to allow
you to directly implement a parser or compiler.
Identifiers
Identifiers begin with an uppercase or lowercase letter A through Z,
an underscore (_), a noncombining alphanumeric Unicode character
in the Basic Multilingual Plane, or a character outside the Basic
Multilingual Plane that isn’t in a Private Use Area. After the first
character, digits and combining Unicode characters are also allowed.
The compiler synthesizes identifiers that begin with a dollar sign ($)
for properties that have a property wrapper projection. Your code can
interact with these identifiers, but you can’t declare identifiers with
that prefix. For more information, see the propertyWrapper section of
the Attributes chapter.
Literals
A literal is the source code representation of a value of a type, such
as a number or string.
1 42 // Integer literal
2 3.14159 // Floating-point literal
3 "Hello, world!" // String literal
4 /Hello, .*/ // Regular expression literal
5 true // Boolean literal
Default
Literal Protocol
type
Floating-
Double ExpressibleByFloatLiteral
point
ExpressibleByStringLiteral,
ExpressibleByUnicodeScalarLiteral for string
literals that contain only a single Unicode scalar,
String String
ExpressibleByExtendedGraphemeClusterLiteral
for string literals that contain only a single
extended grapheme cluster
Regular
Regex None
expression
Integer Literals
Integer literals represent integer values of unspecified precision. By
default, integer literals are expressed in decimal; you can specify an
alternate base using a prefix. Binary literals begin with 0b, octal
literals begin with 0o, and hexadecimal literals begin with 0x.
Underscores (_) are allowed between digits for readability, but they’re
ignored and therefore don’t affect the value of the literal. Integer
literals can begin with leading zeros (0), but they’re likewise ignored
and don’t affect the base or value of the literal.
integer-literal → binary-literal
integer-literal → octal-literal
integer-literal → decimal-literal
integer-literal → hexadecimal-literal
binary-literal → 0b binary-digit binary-literal-characters opt
binary-digit → Digit 0 or 1
binary-literal-character → binary-digit | _
binary-literal-characters → binary-literal-character binary-literal-characters
opt
octal-literal → 0o octal-digit octal-literal-characters opt
octal-digit → Digit 0 through 7
octal-literal-character → octal-digit | _
octal-literal-characters → octal-literal-character octal-literal-characters opt
decimal-literal → decimal-digit decimal-literal-characters opt
decimal-digit → Digit 0 through 9
decimal-digits → decimal-digit decimal-digits opt
decimal-literal-character → decimal-digit | _
decimal-literal-characters → decimal-literal-character decimal-literal-
characters opt
hexadecimal-literal → 0x hexadecimal-digit hexadecimal-literal-characters
opt
hexadecimal-digit → Digit 0 through 9, a through f, or A through F
hexadecimal-literal-character → hexadecimal-digit | _
hexadecimal-literal-characters → hexadecimal-literal-character
hexadecimal-literal-characters opt
Floating-Point Literals
Floating-point literals represent floating-point values of unspecified
precision.
Underscores (_) are allowed between digits for readability, but they’re
ignored and therefore don’t affect the value of the literal. Floating-
point literals can begin with leading zeros (0), but they’re likewise
ignored and don’t affect the base or value of the literal.
String Literals
A string literal is a sequence of characters surrounded by quotation
marks. A single-line string literal is surrounded by double quotation
marks and has the following form:
"""
characters
"""
The line break after the """ that begins the multiline string literal isn’t
part of the string. The line break before the """ that ends the literal is
also not part of the string. To make a multiline string literal that begins
or ends with a line feed, write a blank line as its first or last line.
Line breaks in a multiline string literal are normalized to use the line
feed character. Even if your source file has a mix of carriage returns
and line feeds, all of the line breaks in the string will be the same.
Backslash (\\)
For example, all of the following string literals have the same value:
1 "1 2 3"
2 "1 2 \("3")"
3 "1 2 \(3)"
4 "1 2 \(1 + 2)"
5 let x = 3; "1 2 \(x)"
#"""
characters
"""#
If you use more than one number sign to form a string delimited by
extended delimiters, don’t place whitespace in between the number
signs:
Multiline string literals that you create using extended delimiters have
the same indentation requirements as regular multiline string literals.
/ regular expression /
#/ regular expression /#
#/
regular expression
/#
If you use more than one number sign to form a regular expression
literal delimited by extended delimiters, don’t place whitespace in
between the number signs:
If you need to make an empty regular expression literal, you must use
the extended delimiter syntax.
regular-expression-literal → regular-expression-literal-opening-delimiter
regular-expression regular-expression-literal-closing-delimiter
regular-expression → Any regular expression
regular-expression-literal-opening-delimiter → extended-regular-expression-
literal-delimiter opt /
regular-expression-literal-closing-delimiter → / extended-regular-
expression-literal-delimiter opt
extended-regular-expression-literal-delimiter → # extended-regular-
expression-literal-delimiter opt
Operators
The Swift standard library defines a number of operators for your use,
many of which are discussed in Basic Operators and Advanced
Operators. The present section describes which characters can be
used to define custom operators.
You can also define custom operators that begin with a dot (.). These
operators can contain additional dots. For example, .+. is treated as
a single operator. If an operator doesn’t begin with a dot, it can’t
contain a dot elsewhere. For example, +.+ is treated as the + operator
followed by the .+ operator.
NOTE
The tokens =, ->, //, /*, */, ., the prefix operators <, &, and ?, the infix
operator ?, and the postfix operators >, !, and ? are reserved. These tokens
can’t be overloaded, nor can they be used as custom operators.
In certain constructs, operators with a leading < or > may be split into
two or more tokens. The remainder is treated the same way and may
be split again. As a result, you don’t need to add whitespace to
disambiguate between the closing > characters in constructs like
Dictionary<String, Array<Int>>. In this example, the closing >
characters aren’t treated as a single token that may then be
misinterpreted as a bit shift >> operator.
In Swift, there are two kinds of types: named types and compound
types. A named type is a type that can be given a particular name
when it’s defined. Named types include classes, structures,
enumerations, and protocols. For example, instances of a user-
defined class named MyClass have the type MyClass. In addition to
user-defined named types, the Swift standard library defines many
commonly used named types, including those that represent arrays,
dictionaries, and optional values.
This chapter discusses the types defined in the Swift language itself
and describes the type inference behavior of Swift.
type → function-type
type → array-type
type → dictionary-type
type → type-identifier
type → tuple-type
type → optional-type
type → implicitly-unwrapped-optional-type
type → protocol-composition-type
type → opaque-type
type → metatype-type
type → any-type
type → self-type
type → ( type )
Type Annotation
A type annotation explicitly specifies the type of a variable or
expression. Type annotations begin with a colon (:) and end with a
type, as the following examples show:
G R A M M A R O F A T Y P E A N N O TAT I O N
Most of the time, a type identifier directly refers to a named type with
the same name as the identifier. For example, Int is a type identifier
that directly refers to the named type Int, and the type identifier
Dictionary<String, Int> directly refers to the named type
Dictionary<String, Int>.
There are two cases in which a type identifier doesn’t refer to a type
with the same name. In the first case, a type identifier refers to a type
alias of a named or compound type. For instance, in the example
below, the use of Point in the type annotation refers to the tuple type
(Int, Int).
In the second case, a type identifier uses dot (.) syntax to refer to
named types declared in other modules or nested within other types.
For example, the type identifier in the following code references the
named type MyType that’s declared in the ExampleModule module.
You can use a tuple type as the return type of a function to enable the
function to return a single tuple containing multiple values. You can
also name the elements of a tuple type and use those names to refer
to the values of the individual elements. An element name consists of
an identifier followed immediately by a colon (:). For an example that
demonstrates both of these features, see Functions with Multiple
Return Values.
When an element of a tuple type has a name, that name is part of the
type.
All tuple types contain two or more types, except for Void which is a
type alias for the empty tuple type, ().
If a function type has only one parameter and that parameter’s type is
a tuple type, then the tuple type must be parenthesized when writing
the function’s type. For example, ((Int, Int)) -> Void is the type of
a function that takes a single parameter of the tuple type (Int, Int)
If a function type includes more than a single arrow (->), the function
types are grouped from right to left. For example, the function type
(Int) -> (Int) -> Int is understood as (Int) -> ((Int) -> Int)
—that is, a function that takes an Int and returns another function
that takes and returns an Int.
Function types for functions that can throw or rethrow an error must
be marked with the throws keyword. The throws keyword is part of a
function’s type, and nonthrowing functions are subtypes of throwing
functions. As a result, you can use a nonthrowing function in the
same places as a throwing one. Throwing and rethrowing functions
are described in Throwing Functions and Methods and Rethrowing
Functions and Methods.
The four function calls marked “Error” in the example above cause
compiler errors. Because the first and second parameters are
nonescaping functions, they can’t be passed as arguments to another
nonescaping function parameter. In contrast, the two function calls
marked “OK” don’t cause a compiler error. These function calls don’t
violate the restriction because external isn’t one of the parameters of
takesTwoFunctions(first:second:).
Array Type
The Swift language provides the following syntactic sugar for the
Swift standard library Array<Element> type:
[ type ]
For a detailed discussion of the Swift standard library Array type, see
Arrays.
G R A M M A R O F A N A R R AY T Y P E
array-type → [ type ]
Dictionary Type
The Swift language provides the following syntactic sugar for the
Swift standard library Dictionary<Key, Value> type:
Optional Type
The Swift language defines the postfix ? as syntactic sugar for the
named type Optional<Wrapped>, which is defined in the Swift
1 optionalInteger = 42
2 optionalInteger! // 42
For more information and to see examples that show how to use
optional types, see Optionals.
optional-type → type ?
Note that no whitespace may appear between the type and the !.
G R A M M A R O F A N I M P L I C I T LY U N W R A P P E D O P T I O N A L T Y P E
implicitly-unwrapped-optional-type → type !
Each item in a protocol composition list is one of the following; the list
can contain at most one class:
1 typealias PQ = P & Q
2 typealias PQR = PQ & Q & R
Opaque Type
An opaque type defines a type that conforms to a protocol or protocol
composition, without specifying the underlying concrete type.
some constraint
A function that uses an opaque type as its return type must return
values that share a single underlying type. The return type can
include types that are part of the function’s generic type parameters.
For example, a function someFunction<T>() could return a value of
type T or Dictionary<String, T>.
G R A M M A R O F A N O PA Q U E T Y P E
Metatype Type
A metatype type refers to the type of any type, including class types,
structure types, enumeration types, and protocol types.
You can use the postfix self expression to access a type as a value.
For example, SomeClass.self returns SomeClass itself, not an
instance of SomeClass. And SomeProtocol.self returns SomeProtocol
itself, not an instance of a type that conforms to SomeProtocol at
runtime. You can call the type(of:) function with an instance of a
type to access that instance’s dynamic, runtime type as a value, as
the following example shows:
G R A M M A R O F A M E TAT Y P E T Y P E
Any Type
The Any type can contain values from all other types. Any can be used
as the concrete type for an instance of any of the following types:
When you use Any as a concrete type for an instance, you need to
cast the instance to a known type before you can access its
properties or methods. Instances with a concrete type of Any maintain
their original dynamic type and can be cast to that type using one of
the type-cast operators—as, as?, or as!. For example, use as? to
conditionally downcast the first object in a heterogeneous array to a
String as follows:
The AnyObject protocol is similar to the Any type. All classes implicitly
conform to AnyObject. Unlike Any, which is defined by the language,
AnyObject is defined by the Swift standard library. For more
information, see Class-Only Protocols and AnyObject.
any-type → Any
Self Type
The last part of the example above shows that Self refers to the
runtime type Subclass of the value of z, not the compile-time type
Superclass of the variable itself.
Inside a nested type declaration, the Self type refers to the type
introduced by the innermost type declaration.
The Self type refers to the same type as the type(of:) function in
the Swift standard library. Writing Self.someStaticMember to access
a member of the current type is the same as writing type(of:
self).someStaticMember.
self-type → Self
Class types can inherit from a single superclass and conform to any
number of protocols. When defining a class, the name of the
superclass must appear first in the list of type identifiers, followed by
any number of protocols the class must conform to. If the class
doesn’t inherit from another class, the list can begin with a protocol
instead. For an extended discussion and several examples of class
inheritance, see Inheritance.
G R A M M A R O F A T Y P E I N H E R I TA N C E C L A U S E
type-inheritance-clause → : type-inheritance-list
type-inheritance-list → attributes opt type-identifier | attributes opt type-
identifier , type-inheritance-list
GRAMMAR OF AN EXPRESSION
Prefix Expressions
Prefix expressions combine an optional prefix operator with an
expression. Prefix operators take one argument, the expression that
follows them.
In-Out Expression
An in-out expression marks a variable that’s being passed as an in-
out argument to a function call expression.
& expression
Try Operator
A try expression consists of the try operator followed by an
expression that can throw an error. It has the following form:
try expression
try! expression
If an expression includes both the try and await operator, the try
operator must appear first.
For more information and to see examples of how to use try, try?,
and try!, see Error Handling.
Await Operator
An await expression consists of the await operator followed by an
expression that uses the result of an asynchronous operation. It has
the following form:
If an expression includes both the await and try operator, the try
operator must appear first.
await-operator → await
Infix Expressions
Infix expressions combine an infix binary operator with the
expression that it takes as its left- and right-hand arguments. It has
the following form:
NOTE
Assignment Operator
The assignment operator sets a new value for a given expression. It
has the following form:
expression = value
G R A M M A R O F A N A S S I G N M E N T O P E R AT O R
assignment-operator → =
G R A M M A R O F A C O N D I T I O N A L O P E R AT O R
conditional-operator → ? expression :
Type-Casting Operators
There are four type-casting operators: the is operator, the as
operator, the as? operator, and the as! operator.
The as operator performs a cast when it’s known at compile time that
the cast always succeeds, such as upcasting or bridging. Upcasting
lets you use an expression as an instance of its type’s supertype,
without using an intermediate variable. The following approaches are
equivalent:
For more information about type casting and to see examples that
use the type-casting operators, see Type Casting.
G R A M M A R O F A T Y P E - C A S T I N G O P E R AT O R
type-casting-operator → is type
type-casting-operator → as type
type-casting-operator → as ? type
type-casting-operator → as ! type
Primary Expressions
Primary expressions are the most basic kind of expression. They can
be used as expressions on their own, and they can be combined with
other tokens to make prefix expressions, infix expressions, and
postfix expressions.
Literal Expression
A literal expression consists of either an ordinary literal (such as a
string or a number), an array or dictionary literal, a playground literal,
or one of the following special literals:
To parse a #fileID expression, read the module name as the text before the
first slash (/) and the filename as the text after the last slash. In the future, the
string might contain multiple slashes, such as
MyModule/some/disambiguation/MyFile.swift.
literal-expression → literal
literal-expression → array-literal | dictionary-literal | playground-literal
literal-expression → #file | #fileID | #filePath
literal-expression → #line | #column | #function | #dsohandle
array-literal → [ array-literal-items opt ]
array-literal-items → array-literal-item ,opt | array-literal-item , array-
literal-items
array-literal-item → expression
dictionary-literal → [ dictionary-literal-items ] | [ : ]
dictionary-literal-items → dictionary-literal-item ,opt | dictionary-literal-
item , dictionary-literal-items
dictionary-literal-item → expression : expression
playground-literal → #colorLiteral ( red : expression , green :
expression , blue : expression , alpha : expression )
playground-literal → #fileLiteral ( resourceName : expression )
playground-literal → #imageLiteral ( resourceName : expression )
Self Expression
The self expression is an explicit reference to the current type or
instance of the type in which it occurs. It has the following forms:
self
self. member name
self[ subscript index ]
self( initializer arguments )
self.init( initializer arguments )
1 struct Point {
2 var x = 0.0, y = 0.0
3 mutating func moveBy(x deltaX: Double, y deltaY:
Double) {
4 self = Point(x: x + deltaX, y: y + deltaY)
5 }
6 }
Superclass Expression
A superclass expression lets a class interact with its superclass. It
has one of the following forms:
Closure Expression
A closure expression creates a closure, also known as a lambda or
an anonymous function in other programming languages. Like a
function declaration, a closure contains statements, and it captures
constants and variables from its enclosing scope. It has the following
form:
There are several special forms that allow closures to be written more
concisely:
A closure can omit the types of its parameters, its return type, or
both. If you omit the parameter names and both types, omit the
in keyword before the statements. If the omitted types can’t be
inferred, a compile-time error is raised.
A closure may omit names for its parameters. Its parameters are
then implicitly named $ followed by their position: $0, $1, $2, and
so on.
Capture Lists
The entries in the capture list are initialized when the closure is
created. For each entry in the capture list, a constant is initialized to
the value of the constant or variable that has the same name in the
surrounding scope. For example in the code below, a is included in
the capture list but b is not, which gives them different behavior.
1 var a = 0
2 var b = 0
3 let closure = { [a] in
4 print(a, b)
5 }
6
7 a = 10
8 b = 10
9 closure()
10 // Prints "0 10"
This distinction isn’t visible when the captured variable’s type has
reference semantics. For example, there are two things named x in
the code below, a variable in the outer scope and a constant in the
inner scope, but they both refer to the same object because of
reference semantics.
1 class SimpleClass {
2 var value: Int = 0
3 }
4 var x = SimpleClass()
5 var y = SimpleClass()
6 let closure = { [x] in
7 print(x.value, y.value)
8 }
9
10 x.value = 10
11 y.value = 10
12 closure()
13 // Prints "10 10"
If the type of the expression’s value is a class, you can mark the
expression in a capture list with weak or unowned to capture a weak or
unowned reference to the expression’s value.
. member name
For example:
1 var x = MyEnumeration.someValue
2 x = .anotherValue
1 class SomeClass {
2 static var shared = SomeClass()
3 static var sharedSubclass = SomeSubclass()
4 var a = AnotherClass()
5 }
6 class SomeSubclass: SomeClass { }
7 class AnotherClass {
8 static var s = SomeClass()
9 func f() -> SomeClass { return AnotherClass.s }
10 }
11 let x: SomeClass = .shared.a.f()
12 let y: SomeClass? = .shared
13 let z: SomeClass = .sharedSubclass
implicit-member-expression → . identifier
implicit-member-expression → . identifier . postfix-expression
Parenthesized Expression
A parenthesized expression consists of an expression surrounded by
parentheses. You can use parentheses to specify the precedence of
operations by explicitly grouping expressions. Grouping parentheses
don’t change an expression’s type—for example, the type of (1) is
simply Int.
G R A M M A R O F A PA R E N T H E S I Z E D E X P R E S S I O N
parenthesized-expression → ( expression )
Tuple Expression
A tuple expression consists of a comma-separated list of expressions
surrounded by parentheses. Each expression can have an optional
identifier before it, separated by a colon (:). It has the following form:
NOTE
Both an empty tuple expression and an empty tuple type are written () in
Swift. Because Void is a type alias for (), you can use it to write an empty
tuple type. However, like all type aliases, Void is always a type—you can’t use
it to write an empty tuple expression.
Wildcard Expression
A wildcard expression is used to explicitly ignore a value during an
assignment. For example, in the following assignment 10 is assigned
to x and 20 is ignored:
wildcard-expression → _
Key-Path Expression
The type name is the name of a concrete type, including any generic
parameters, such as String, [Int], or Set<Int>.
To access a value using a key path, pass the key path to the
subscript(keyPath:) subscript, which is available on all types. For
example:
1 struct SomeStructure {
2 var someValue: Int
3 }
4
5 let s = SomeStructure(someValue: 12)
6 let pathToProperty = \SomeStructure.someValue
7
8 let value = s[keyPath: pathToProperty]
9 // value is 12
The path can refer to self to create the identity key path (\.self).
The identity key path refers to a whole instance, so you can use it to
access and change all of the data stored in a variable in a single step.
For example:
You can mix and match components of key paths to access values
that are deeply nested within a type. The following code accesses
different values and properties of a dictionary of arrays by using key-
path expressions that combine these components.
You can use a key path expression in contexts where you would
normally provide a function or closure. Specifically, you can use a key
path expression whose root type is SomeType and whose path
produces a value of type Value, instead of a function or closure of
type (SomeType) -> Value.
Any side effects of a key path expression are evaluated only at the
point where the expression is evaluated. For example, if you make a
function call inside a subscript in a key path expression, the function
is called only once as part of evaluating the expression, not every
time the key path is used.
For more information about using key paths in code that interacts
with Objective-C APIs, see Using Objective-C Runtime Features in
Swift. For information about key-value coding and key-value
observing, see Key-Value Coding Programming Guide and Key-
Value Observing Programming Guide.
G R A M M A R O F A K E Y- PAT H E X P R E S S I O N
Selector Expression
A selector expression lets you access the selector used to refer to a
method or to a property’s getter or setter in Objective-C. It has the
following form:
1 extension SomeClass {
2 @objc(doSomethingWithString:)
3 func doSomething(_ x: String) { }
4 }
5 let anotherSelector =
#selector(SomeClass.doSomething(_:) as
(SomeClass) -> (String) -> Void)
NOTE
Although the method name and the property name are expressions, they’re
never evaluated.
When you use a key-path string expression within a class, you can
refer to a property of that class by writing just the property name,
without the class name.
Because the key path string is created at compile time, not at runtime,
the compiler can check that the property exists and that the property
is exposed to the Objective-C runtime.
For more information about using key paths in Swift code that
interacts with Objective-C APIs, see Using Objective-C Runtime
Features in Swift. For information about key-value coding and key-
value observing, see Key-Value Coding Programming Guide and
Key-Value Observing Programming Guide.
NOTE
G R A M M A R O F A K E Y- PAT H S T R I N G E X P R E S S I O N
Postfix Expressions
Postfix expressions are formed by applying a postfix operator or other
postfix syntax to an expression. Syntactically, every primary
expression is also a postfix expression.
postfix-expression → primary-expression
postfix-expression → postfix-expression postfix-operator
postfix-expression → function-call-expression
postfix-expression → initializer-expression
postfix-expression → explicit-member-expression
postfix-expression → postfix-self-expression
postfix-expression → subscript-expression
postfix-expression → forced-value-expression
postfix-expression → optional-chaining-expression
If the trailing closure is the function’s only argument, you can omit the
parentheses.
Trailing
Parameter Action
Closure
The trailing closure is passed as the argument for the parameter that
it matches. Parameters that were skipped during the scanning
process don’t have an argument passed to them—for example, they
can use a default parameter. After finding a match, scanning
continues with the next trailing closure and the next parameter. At the
end of the matching process, all trailing closures must have a match.
NOTE
Initializer Expression
An initializer expression provides access to a type’s initializer. It has
the following form:
If you specify a type by name, you can access the type’s initializer
without using an initializer expression. In all other cases, you must
use an initializer expression.
1 class SomeClass {
2 var someProperty = 42
3 }
4 let c = SomeClass()
5 let y = c.someProperty // Member access
1 class SomeClass {
2 func someMethod(x: Int, y: Int) {}
3 func someMethod(x: Int, z: Int) {}
4 func overloadedMethod(x: Int, y: Int) {}
5 func overloadedMethod(x: Int, y: Bool) {}
6 }
7 let instance = SomeClass()
8
9 let a = instance.someMethod //
Ambiguous
10 let b = instance.someMethod(x:y:) //
Unambiguous
11
12 let d = instance.overloadedMethod //
Ambiguous
13 let d = instance.overloadedMethod(x:y:) // Still
ambiguous
14 let d: (Int, Bool) -> Void =
instance.overloadedMethod(x:y:) // Unambiguous
You can combine this multiline chained syntax with compiler control
statements to control when each method is called. For example, the
following code uses a different filtering rule on iOS:
You can use this syntax anywhere that you can write an explicit
member expression, not just in top-level code.
expression .self
type .self
The first form evaluates to the value of the expression. For example,
x.self evaluates to x.
The second form evaluates to the value of the type. Use this form to
access a type as a value. For example, because SomeClass.self
evaluates to the SomeClass type itself, you can pass it to a function or
method that accepts a type-level argument.
Subscript Expression
Forced-Value Expression
A forced-value expression unwraps an optional value that you are
certain isn’t nil. It has the following form:
expression !
G R A M M A R O F A F O R C E D - VA L U E E X P R E S S I O N
forced-value-expression → postfix-expression !
Optional-Chaining Expression
An optional-chaining expression provides a simplified syntax for
using optional values in postfix expressions. It has the following form:
expression ?
1 var c: SomeClass?
2 var result: Bool? = c?.property.performAction()
optional-chaining-expression → postfix-expression ?
In Swift, there are three kinds of statements: simple statements, compiler control
statements, and control flow statements. Simple statements are the most
common and consist of either an expression or a declaration. Compiler control
statements allow the program to change aspects of the compiler’s behavior and
include a conditional compilation block and a line control statement.
Control flow statements are used to control the flow of execution in a program.
There are several types of control flow statements in Swift, including loop
statements, branch statements, and control transfer statements. Loop
statements allow a block of code to be executed repeatedly, branch statements
allow a certain block of code to be executed only when certain conditions are
met, and control transfer statements provide a way to alter the order in which
code is executed. In addition, Swift provides a do statement to introduce scope,
and catch and handle errors, and a defer statement for running cleanup actions
just before the current scope exits.
A semicolon (;) can optionally appear after any statement and is used to
separate multiple statements if they appear on the same line.
G R A M M A R O F A S TAT E M E N T
Loop Statements
Loop statements allow a block of code to be executed repeatedly, depending on
the conditions specified in the loop. Swift has three loop statements: a for-in
G R A M M A R O F A L O O P S TAT E M E N T
loop-statement → for-in-statement
loop-statement → while-statement
loop-statement → repeat-while-statement
For-In Statement
A for-in statement allows a block of code to be executed once for each item in
a collection (or any type) that conforms to the Sequence protocol.
G R A M M A R O F A F O R - I N S TAT E M E N T
While Statement
A while statement allows a block of code to be executed repeatedly, as long as
a condition remains true.
Because the value of the condition is evaluated before the statements are
executed, the statements in a while statement can be executed zero or more
times.
The value of the condition must be of type Bool or a type bridged to Bool. The
condition can also be an optional binding declaration, as discussed in Optional
Binding.
G R A M M A R O F A W H I L E S TAT E M E N T
Repeat-While Statement
A repeat-while statement allows a block of code to be executed one or more
times, as long as a condition remains true.
repeat {
statements
} while condition
Because the value of the condition is evaluated after the statements are
executed, the statements in a repeat-while statement are executed at least
once.
The value of the condition must be of type Bool or a type bridged to Bool. The
condition can also be an optional binding declaration, as discussed in Optional
Binding.
G R A M M A R O F A R E P E AT - W H I L E S TAT E M E N T
Branch Statements
Branch statements allow the program to execute certain parts of code
depending on the value of one or more conditions. The values of the conditions
specified in a branch statement control how the program branches and,
therefore, what block of code is executed. Swift has three branch statements: an
if statement, a guard statement, and a switch statement.
G R A M M A R O F A B R A N C H S TAT E M E N T
branch-statement → if-statement
branch-statement → guard-statement
branch-statement → switch-statement
If Statement
There are two basic forms of an if statement. In each form, the opening and
closing braces are required.
The first form allows code to be executed only when a condition is true and has
the following form:
if condition {
statements
}
if condition {
statements to execute if condition is true
} else {
statements to execute if condition is false
}
if condition 1 {
statements to execute if condition 1 is true
} else if condition 2 {
statements to execute if condition 2 is true
} else {
statements to execute if both conditions are false
}
G R A M M A R O F A N I F S TAT E M E N T
Guard Statement
A guard statement is used to transfer program control out of a scope if one or
more conditions aren’t met.
The value of any condition in a guard statement must be of type Bool or a type
bridged to Bool. The condition can also be an optional binding declaration, as
discussed in Optional Binding.
The else clause of a guard statement is required, and must either call a function
with the Never return type or transfer program control outside the guard
statement’s enclosing scope using one of the following statements:
return
break
continue
throw
G R A M M A R O F A G U A R D S TAT E M E N T
Switch Statement
A switch statement allows certain blocks of code to be executed depending on
the value of a control expression.
The control expression of the switch statement is evaluated and then compared
with the patterns specified in each case. If a match is found, the program
executes the statements listed within the scope of that case. The scope of each
case can’t be empty. As a result, you must include at least one statement
following the colon (:) of each case label. Use a single break statement if you
don’t intend to execute any code in the body of a matched case.
The values of expressions your code can branch on are very flexible. For
example, in addition to the values of scalar types, such as integers and
characters, your code can branch on the values of any type, including floating-
point numbers, strings, tuples, instances of custom classes, and optionals. The
value of the control expression can even be matched to the value of a case in
an enumeration and checked for inclusion in a specified range of values. For
A switch case can optionally contain a where clause after each pattern. A where
clause is introduced by the where keyword followed by an expression, and is
used to provide an additional condition before a pattern in a case is considered
matched to the control expression. If a where clause is present, the statements
within the relevant case are executed only if the value of the control expression
matches one of the patterns of the case and the expression of the where clause
evaluates to true. For example, a control expression matches the case in the
example below only if it’s a tuple that contains two elements of the same value,
such as (1, 1).
As the above example shows, patterns in a case can also bind constants using
the let keyword (they can also bind variables using the var keyword). These
constants (or variables) can then be referenced in a corresponding where clause
and throughout the rest of the code within the scope of the case. If the case
contains multiple patterns that match the control expression, all of the patterns
must contain the same constant or variable bindings, and each bound variable
or constant must have the same type in all of the case’s patterns.
A switch statement can also include a default case, introduced by the default
keyword. The code within a default case is executed only if no other cases
match the control expression. A switch statement can include only one default
case, which must appear at the end of the switch statement.
In Swift, every possible value of the control expression’s type must match the
value of at least one pattern of a case. When this simply isn’t feasible (for
The following example switches over all three existing cases of the standard
library’s Mirror.AncestorRepresentation enumeration. If you add additional
cases in the future, the compiler generates a warning to indicate that you need
to update the switch statement to take the new cases into account.
After the code within a matched case has finished executing, the program exits
from the switch statement. Program execution doesn’t continue or “fall through”
to the next case or default case. That said, if you want execution to continue
from one case to the next, explicitly include a fallthrough statement, which
simply consists of the fallthrough keyword, in the case from which you want
execution to continue. For more information about the fallthrough statement,
see Fallthrough Statement below.
Labeled Statement
You can prefix a loop statement, an if statement, a switch statement, or a do
statement with a statement label, which consists of the name of the label
followed immediately by a colon (:). Use statement labels with break and
continue statements to be explicit about how you want to change control flow in
a loop statement or a switch statement, as discussed in Break Statement and
Continue Statement below.
The scope of a labeled statement is the entire statement following the statement
label. You can nest labeled statements, but the name of each statement label
must be unique.
For more information and to see examples of how to use statement labels, see
Labeled Statements in Control Flow.
G R A M M A R O F A C O N T R O L T R A N S F E R S TAT E M E N T
control-transfer-statement → break-statement
control-transfer-statement → continue-statement
control-transfer-statement → fallthrough-statement
control-transfer-statement → return-statement
control-transfer-statement → throw-statement
Break Statement
A break statement ends program execution of a loop, an if statement, or a
switch statement. A break statement can consist of only the break keyword, or it
can consist of the break keyword followed by the name of a statement label, as
shown below.
break
break label name
In both cases, program control is then transferred to the first line of code
following the enclosing loop or switch statement, if any.
For examples of how to use a break statement, see Break and Labeled
Statements in Control Flow.
G R A M M A R O F A B R E A K S TAT E M E N T
Continue Statement
A continue statement ends program execution of the current iteration of a loop
statement but doesn’t stop execution of the loop statement. A continue
statement can consist of only the continue keyword, or it can consist of the
continue keyword followed by the name of a statement label, as shown below.
continue
continue label name
In a for statement, the increment expression is still evaluated after the continue
statement is executed, because the increment expression is evaluated after the
execution of the loop’s body.
G R A M M A R O F A C O N T I N U E S TAT E M E N T
Fallthrough Statement
A fallthrough statement consists of the fallthrough keyword and occurs only
in a case block of a switch statement. A fallthrough statement causes
program execution to continue from one case in a switch statement to the next
case. Program execution continues to the next case even if the patterns of the
case label don’t match the value of the switch statement’s control expression.
G R A M M A R O F A F A L LT H R O U G H S TAT E M E N T
fallthrough-statement → fallthrough
Return Statement
A return statement occurs in the body of a function or method definition and
causes program execution to return to the calling function or method. Program
execution continues at the point immediately following the function or method
call.
A return statement can consist of only the return keyword, or it can consist of
the return keyword followed by an expression, as shown below.
return
return expression
NOTE
As described in Failable Initializers, a special form of the return statement (return nil)
can be used in a failable initializer to indicate initialization failure.
G R A M M A R O F A R E T U R N S TAT E M E N T
Throw Statement
A throw statement occurs in the body of a throwing function or method, or in the
body of a closure expression whose type is marked with the throws keyword.
A throw statement causes a program to end execution of the current scope and
begin error propagation to its enclosing scope. The error that’s thrown continues
to propagate until it’s handled by a catch clause of a do statement.
throw expression
The value of the expression must have a type that conforms to the Error
protocol.
For an example of how to use a throw statement, see Propagating Errors Using
Throwing Functions in Error Handling.
G R A M M A R O F A T H R O W S TAT E M E N T
defer {
statements
}
The statements within the defer statement are executed no matter how
program control is transferred. This means that a defer statement can be used,
for example, to perform manual resource management such as closing file
descriptors, and to perform actions that need to happen even if an error is
thrown.
If multiple defer statements appear in the same scope, the order they appear is
the reverse of the order they’re executed. Executing the last defer statement in
a given scope first means that statements inside that last defer statement can
refer to resources that will be cleaned up by other defer statements.
1 func f() {
2 defer { print("First defer") }
3 defer { print("Second defer") }
4 print("End of function")
5 }
6 f()
7 // Prints "End of function"
8 // Prints "Second defer"
9 // Prints "First defer"
The statements in the defer statement can’t transfer program control outside of
the defer statement.
Do Statement
The do statement is used to introduce a new scope and can optionally contain
one or more catch clauses, which contain patterns that match against defined
error conditions. Variables and constants declared in the scope of a do
statement can be accessed only within that scope.
do {
try expression
statements
} catch pattern 1 {
statements
} catch pattern 2 where condition {
statements
} catch pattern 3 , pattern 4 where condition {
statements
} catch {
statements
}
Like a switch statement, the compiler attempts to infer whether catch clauses
are exhaustive. If such a determination can be made, the error is considered
A catch clause that has multiple patterns matches the error if any of its patterns
match the error. If a catch clause contains multiple patterns, all of the patterns
must contain the same constant or variable bindings, and each bound variable
or constant must have the same type in all of the catch clause’s patterns.
To ensure that an error is handled, use a catch clause with a pattern that
matches all errors, such as a wildcard pattern (_). If a catch clause doesn’t
specify a pattern, the catch clause matches and binds any error to a local
constant named error. For more information about the patterns you can use in
a catch clause, see Patterns.
To see an example of how to use a do statement with several catch clauses, see
Handling Errors.
G R A M M A R O F A D O S TAT E M E N T
G R A M M A R O F A C O M P I L E R C O N T R O L S TAT E M E N T
compiler-control-statement → conditional-compilation-block
compiler-control-statement → line-control-statement
compiler-control-statement → diagnostic-statement
Every conditional compilation block begins with the #if compilation directive
and ends with the #endif compilation directive. A simple conditional compilation
block has the following form:
The compilation condition can include the true and false Boolean literals, an
identifier used with the -D command line flag, or any of the platform conditions
listed in the table below.
1 #if compiler(>=5)
2 print("Compiled with the Swift 5 compiler or later")
3 #endif
4 #if swift(>=4.2)
5 print("Compiled in Swift 4.2 mode or later")
6 #endif
7 #if compiler(>=5) && swift(<5)
8 print("Compiled with the Swift 5 compiler or later in a Swift
mode earlier than 5")
9 #endif
10 // Prints "Compiled with the Swift 5 compiler or later"
11 // Prints "Compiled in Swift 4.2 mode or later"
12 // Prints "Compiled with the Swift 5 compiler or later in a
Swift mode earlier than 5"
The argument for the canImport() platform condition is the name of a module
that may not be present on all platforms. The module can include periods (.) in
its name. This condition tests whether it’s possible to import the module, but
doesn’t actually import it. If the module is present, the platform condition returns
true; otherwise, it returns false.
The arch(arm) platform condition doesn’t return true for ARM 64 devices. The
arch(i386) platform condition returns true when code is compiled for the 32–bit iOS
simulator.
You can combine and negate compilation conditions using the logical operators
&&, ||, and ! and use parentheses for grouping. These operators have the same
associativity and precedence as the logical operators that are used to combine
ordinary Boolean expressions.
Similar to an if statement, you can add multiple conditional branches to test for
different compilation conditions. You can add any number of additional branches
using #elseif clauses. You can also add a final additional branch using an
#else clause. Conditional compilation blocks that contain multiple branches
have the following form:
#endif
NOTE
Each statement in the body of a conditional compilation block is parsed even if it’s not
compiled. However, there’s an exception if the compilation condition includes a swift() or
compiler() platform condition: The statements are parsed only if the language or
compiler version matches what is specified in the platform condition. This exception
ensures that an older compiler doesn’t attempt to parse syntax introduced in a newer
version of Swift.
For information about how you can wrap explicit member expressions in
conditional compilation blocks, see Explicit Member Expression.
G R A M M A R O F A L I N E C O N T R O L S TAT E M E N T
The first form emits the error message as a fatal error and terminates the
compilation process. The second form emits the warning message as a nonfatal
warning and allows compilation to proceed. You write the diagnostic message
as a static string literal. Static string literals can’t use features like string
interpolation or concatenation, but they can use the multiline string literal syntax.
G R A M M A R O F A C O M P I L E - T I M E D I A G N O S T I C S TAT E M E N T
} else {
statements to execute if the APIs are available
}
G R A M M A R O F A N AVA I L A B I L I T Y C O N D I T I O N
G R A M M A R O F A D E C L A R AT I O N
declaration → import-declaration
declaration → constant-declaration
declaration → variable-declaration
declaration → typealias-declaration
declaration → function-declaration
declaration → enum-declaration
declaration → struct-declaration
declaration → class-declaration
declaration → actor-declaration
declaration → protocol-declaration
declaration → initializer-declaration
declaration → deinitializer-declaration
declaration → extension-declaration
declaration → subscript-declaration
declaration → operator-declaration
declaration → precedence-group-declaration
declarations → declaration declarations opt
G R A M M A R O F A T O P - L E V E L D E C L A R AT I O N
Code Blocks
A code block is used by a variety of declarations and control
structures to group statements together. It has the following form:
Import Declaration
An import declaration lets you access symbols that are declared
outside the current file. The basic form imports the entire module; it
consists of the import keyword followed by a module name:
import module
Constant Declaration
A constant declaration introduces a constant named value into your
program. Constant declarations are declared using the let keyword
and have the following form:
For more information about constants and for guidance about when
to use them, see Constants and Variables and Stored Properties.
G R A M M A R O F A C O N S TA N T D E C L A R AT I O N
NOTE
Unlike stored named values and stored variable properties, the value
of a computed named value or a computed property isn’t stored in
memory.
You can add property observers to any stored property. You can also
add property observers to any inherited property (whether stored or
computed) by overriding the property within a subclass, as described
in Overriding Property Observers.
If the body of the didSet observer refers to the old value, the getter is
called before the observer, to make the old value available.
Otherwise, the new value is stored without calling the superclass’s
getter. The example below shows a computed property that’s defined
by the superclass and overridden by its subclasses to add an
observer.
After a type alias is declared, the aliased name can be used instead
of the existing type everywhere in your program. The existing type
can be a named type or a compound type. Type aliases don’t create
new types; they simply allow a name to refer to an existing type.
1 typealias StringDictionary<Value> =
Dictionary<String, Value>
2
3 // The following dictionaries have the same type.
4 var dictionary1: StringDictionary<Int> = [:]
5 var dictionary2: Dictionary<String, Int> = [:]
Because the type alias and the existing type can be used
interchangeably, the type alias can’t introduce additional generic
constraints.
Inside a protocol declaration, a type alias can give a shorter and more
convenient name to a type that’s used frequently. For example:
1 protocol Sequence {
2 associatedtype Iterator: IteratorProtocol
3 typealias Element = Iterator.Element
4 }
5
6 func sum<T: Sequence>(_ sequence: T) -> Int where
T.Element == Int {
7 // ...
8 }
Without this type alias, the sum function would have to refer to the
associated type as T.Iterator.Element instead of T.Element.
G R A M M A R O F A T Y P E A L I A S D E C L A R AT I O N
If the function has a return type of Void, the return type can be
omitted as follows:
Functions can return multiple values using a tuple type as the return
type of the function.
Parameter Names
Function parameters are a comma-separated list where each
parameter has one of several forms. The order of arguments in a
function call must match the order of parameters in the function’s
declaration. The simplest entry in a parameter list has the following
form:
You can override the default behavior for argument labels with one of
the following forms:
In-Out Parameters
In-out parameters are passed as follows:
_ : parameter type
parameter name : parameter type ...
parameter name : parameter type =
default argument value
A parameter with an equals sign (=) and an expression after its type
is understood to have a default value of the given expression. The
given expression is evaluated when the function is called. If the
parameter is omitted when calling the function, the default value is
used instead.
You can’t overload a function based only on whether the function can
throw an error. That said, you can overload a function based on
whether a function parameter can throw an error.
You can override a nonreturning method, but the new method must
preserve its return type and nonreturning behavior.
G R A M M A R O F A F U N C T I O N D E C L A R AT I O N
In this form, each case block consists of the case keyword followed
by one or more enumeration cases, separated by commas. The
name of each case must be unique. Each case can also specify that it
stores values of a given type. These types are specified in the
associated value types tuple, immediately following the name of the
case.
Enumerations can have a recursive structure, that is, they can have
cases with associated values that are instances of the enumeration
type itself. However, instances of enumeration types have value
semantics, which means they have a fixed layout in memory. To
support recursion, the compiler must insert a layer of indirection.
In this form, each case block consists of the case keyword, followed
by one or more enumeration cases, separated by commas. Unlike the
cases in the first form, each case has an underlying value, called a
raw value, of the same basic type. The type of these values is
specified in the raw-value type and must represent an integer,
If the raw-value type is specified as Int and you don’t assign a value
to the cases explicitly, they’re implicitly assigned the values 0, 1, 2,
and so on. Each unassigned case of type Int is implicitly assigned a
raw value that’s automatically incremented from the raw value of the
previous case.
Structure Declaration
Structure types can adopt any number of protocols, but can’t inherit
from classes, enumerations, or other structures.
G R A M M A R O F A S T R U C T U R E D E C L A R AT I O N
Class Declaration
A class declaration introduces a named class type into your program.
Class declarations are declared using the class keyword and have
the following form:
A class type can inherit from only one parent class, its superclass, but
can adopt any number of protocols. The superclass appears first after
the class name and colon, followed by any adopted protocols.
Generic classes can inherit from other generic and nongeneric
classes, but a nongeneric class can inherit only from other
nongeneric classes. When you write the name of a generic
superclass class after the colon, you must include the full name of
that generic class, including its generic parameter clause.
Actor Declaration
An actor declaration introduces a named actor type into your
program. Actor declarations are declared using the actor keyword
and have the following form:
Actor types can adopt any number of protocols, but can’t inherit from
classes, enumerations, structures, or other actors. However, an actor
that is marked with the @objc attribute implicitly conforms to the
G R A M M A R O F A N A C T O R D E C L A R AT I O N
Protocol Declaration
A protocol declaration introduces a named protocol type into your
program. Protocol declarations are declared at global scope using the
protocol keyword and have the following form:
Protocol types can inherit from any number of other protocols. When
a protocol type inherits from other protocols, the set of requirements
from those other protocols are aggregated, and any type that inherits
from the current protocol must conform to all those requirements. For
an example of how to use protocol inheritance, see Protocol
Inheritance.
NOTE
1 protocol SomeProtocol {
2 static var someValue: Self { get }
3 static func someFunction(x: Int) -> Self
4 }
5 enum MyEnum: SomeProtocol {
6 case someValue
7 case someFunction(x: Int)
8 }
Any protocol that inherits from a protocol that’s marked with the
AnyObject requirement can likewise be adopted only by class types.
Protocols are named types, and thus they can appear in all the same
places in your code as other named types, as discussed in Protocols
as Types. However, you can’t construct an instance of a protocol,
because protocols don’t actually provide the implementations for the
requirements they specify.
G R A M M A R O F A P R O T O C O L D E C L A R AT I O N
G R A M M A R O F A P R O T O C O L P R O P E R T Y D E C L A R AT I O N
G R A M M A R O F A P R O T O C O L M E T H O D D E C L A R AT I O N
G R A M M A R O F A P R O T O C O L I N I T I A L I Z E R D E C L A R AT I O N
G R A M M A R O F A P R O T O C O L S U B S C R I P T D E C L A R AT I O N
G R A M M A R O F A P R O T O C O L A S S O C I AT E D T Y P E D E C L A R AT I O N
Initializer Declaration
An initializer declaration introduces an initializer for a class, structure,
or enumeration into your program. Initializer declarations are
declared using the init keyword and have two basic forms.
init( parameters ) {
statements
}
NOTE
If you mark an initializer with the required declaration modifier, you don’t also
mark the initializer with the override modifier when you override the required
initializer in a subclass.
1 struct SomeStruct {
2 let property: String
3 // produces an optional instance of 'SomeStruct'
4 init?(input: String) {
5 if input.isEmpty {
6 // discard 'self' and return 'nil'
7 return nil
8 }
9 property = input
10 }
11 }
You call an init? failable initializer in the same way that you call a
nonfailable initializer, except that you must deal with the optionality of
the result.
Deinitializer Declaration
A deinitializer declaration declares a deinitializer for a class type.
Deinitializers take no parameters and have the following form:
deinit {
statements
}
G R A M M A R O F A D E I N I T I A L I Z E R D E C L A R AT I O N
Extension Declaration
An extension declaration allows you to extend the behavior of
existing types. Extension declarations are declared using the
extension keyword and have the following form:
Conditional Conformance
You can extend a generic type to conditionally conform to a protocol,
so that instances of the type conform to the protocol only when
certain requirements are met. You add conditional conformance to a
protocol by including requirements in an extension declaration.
G R A M M A R O F A N E X T E N S I O N D E C L A R AT I O N
Subscript Declaration
A subscript declaration allows you to add subscripting support for
objects of a particular type and are typically used to provide a
convenient syntax for accessing the elements in a collection, list, or
sequence. Subscript declarations are declared using the subscript
keyword and have the following form:
Operator Declaration
An operator declaration introduces a new infix, prefix, or postfix
operator into your program and is declared using the operator
keyword.
You can declare operators of three different fixities: infix, prefix, and
postfix. The fixity of an operator specifies the relative position of an
operator to its operands.
There are three basic forms of an operator declaration, one for each
fixity. The fixity of the operator is specified by marking the operator
declaration with the infix, prefix, or postfix declaration modifier
before the operator keyword. In each form, the name of the operator
can contain only the operator characters defined in Operators.
G R A M M A R O F A N O P E R AT O R D E C L A R AT I O N
The lower group names and higher group names lists specify the new
precedence group’s relation to existing precedence groups. The
lowerThan precedence group attribute may only be used to refer to
NOTE
Precedence groups related to each other using lower group names and higher
group names must fit into a single relational hierarchy, but they don’t have to
form a linear hierarchy. This means it’s possible to have precedence groups
with undefined relative precedence. Operators from those precedence groups
can’t be used next to each other without grouping parentheses.
G R A M M A R O F A P R E C E D E N C E G R O U P D E C L A R AT I O N
Declaration Modifiers
Declaration modifiers are keywords or context-sensitive keywords
that modify the behavior or meaning of a declaration. You specify a
declaration modifier by writing the appropriate keyword or context-
sensitive keyword between a declaration’s attributes (if any) and the
keyword that introduces the declaration.
class
dynamic
final
lazy
optional
You can apply the optional modifier only to protocols that are
marked with the objc attribute. As a result, only class types can
adopt and conform to a protocol that contains optional member
requirements. For more information about how to use the
optional modifier and for guidance about how to access optional
protocol members—for example, when you’re not sure whether a
conforming type implements them—see Optional Protocol
Requirements.
required
static
unowned
unowned(safe)
unowned(unsafe)
weak
open
public
internal
fileprivate
private
For the purpose of access control, extensions to the same type that
are in the same file share an access-control scope. If the type they
extend is also in the same file, they share the type’s access-control
scope. Private members declared in the type’s declaration can be
accessed from extensions, and private members declared in one
extension can be accessed from other extensions and from the type’s
declaration.
G R A M M A R O F A D E C L A R AT I O N M O D I F I E R
@ attribute name
@ attribute name ( attribute arguments )
Declaration Attributes
You can apply a declaration attribute to declarations only.
available
Apply this attribute to indicate a declaration’s life cycle relative to
certain Swift language versions or certain platforms and operating
system versions.
iOS
iOSApplicationExtension
macOS
macOSApplicationExtension
macCatalyst
macCatalystApplicationExtension
watchOS
watchOSApplicationExtension
tvOS
tvOSApplicationExtension
swift
You can also use an asterisk (*) to indicate the availability of the
declaration on all of the platform names listed above. An available
attribute that specifies availability using a Swift version number can’t
use the asterisk.
message: message
You can apply the available attribute with the renamed and
unavailable arguments to a type alias declaration, as shown
below, to indicate that the name of a declaration changed
between releases of a framework or library. This combination
results in a compile-time error that the declaration has been
renamed.
1 // First release
2 protocol MyProtocol {
3 // protocol definition
4 }
1 @available(swift 3.0.2)
2 @available(macOS 10.12, *)
3 struct MyStruct {
4 // struct definition
5 }
discardableResult
Apply this attribute to a function or method declaration to suppress
the compiler warning when the function or method that returns a
value is called without using its result.
dynamicCallable
Apply this attribute to a class, structure, enumeration, or protocol to
treat instances of the type as callable functions. The type must
implement either a dynamicallyCall(withArguments:) method, a
dynamicallyCall(withKeywordArguments:) method, or both.
You can include labels in a dynamic method call if you implement the
dynamicallyCall(withKeywordArguments:) method.
1 @dynamicCallable
2 struct Repeater {
3 func dynamicallyCall(withKeywordArguments pairs:
KeyValuePairs<String, Int>) -> String {
4 return pairs
5 .map { label, count in
6 repeatElement(label, count:
count).joined(separator: " ")
7 }
8 .joined(separator: "\n")
9 }
10 }
11
12 let repeatLabels = Repeater()
13 print(repeatLabels(a: 1, b: 2, c: 3, b: 2, a: 1))
14 // a
15 // b b
16 // c c c
17 // b b
18 // a
You can only call a dynamically callable instance with arguments and
a return value that match the types you specify in one of your
dynamicallyCall method implementations. The call in the following
example doesn’t compile because there isn’t an implementation of
dynamicallyCall(withArguments:) that takes
KeyValuePairs<String, String>.
dynamicMemberLookup
Apply this attribute to a class, structure, enumeration, or protocol to
enable members to be looked up by name at runtime. The type must
implement a subscript(dynamicMember:) subscript.
frozen
Apply this attribute to a structure or enumeration declaration to
restrict the kinds of changes you can make to the type. This attribute
is allowed only when compiling in library evolution mode. Future
versions of the library can’t change the declaration by adding,
removing, or reordering an enumeration’s cases or a structure’s
stored instance properties. These changes are allowed on nonfrozen
types, but they break ABI compatibility for frozen types.
NOTE
When the compiler isn’t in library evolution mode, all structures and
enumerations are implicitly frozen, and this attribute is ignored.
GKInspectable
Apply this attribute to expose a custom GameplayKit component
property to the SpriteKit editor UI. Applying this attribute also implies
the objc attribute.
main
Apply this attribute to a structure, class, or enumeration declaration to
indicate that it contains the top-level entry point for program flow. The
type must provide a main type function that doesn’t take any
arguments and returns Void. For example:
1 @main
2 struct MyTopLevel {
3 static func main() {
4 // Top-level code goes here
5 }
6 }
1 protocol ProvidesMain {
2 static func main() throws
3 }
nonobjc
Apply this attribute to a method, property, subscript, or initializer
declaration to suppress an implicit objc attribute. The nonobjc
attribute tells the compiler to make the declaration unavailable in
Objective-C code, even though it’s possible to represent it in
Objective-C.
NSApplicationMain
Apply this attribute to a class to indicate that it’s the application
delegate. Using this attribute is equivalent to calling the
NSApplicationMain(_:_:) function.
If you don’t use this attribute, supply a main.swift file with code at the
top level that calls the NSApplicationMain(_:_:) function as follows:
1 import AppKit
2 NSApplicationMain(CommandLine.argc,
CommandLine.unsafeArgv)
NSCopying
Apply this attribute to a stored variable property of a class. This
attribute causes the property’s setter to be synthesized with a copy of
the property’s value—returned by the copyWithZone(_:) method—
instead of the value of the property itself. The type of the property
must conform to the NSCopying protocol.
NSManaged
objc
Apply this attribute to any declaration that can be represented in
Objective-C—for example, nonnested classes, protocols, nongeneric
enumerations (constrained to integer raw-value types), properties
and methods (including getters and setters) of classes, protocols and
optional members of a protocol, initializers, and subscripts. The objc
attribute tells the compiler that a declaration is available to use in
Objective-C code.
The argument to the objc attribute can also change the runtime name for that
declaration. You use the runtime name when calling functions that interact
with the Objective-C runtime, like NSClassFromString, and when specifying
class names in an app’s Info.plist file. If you specify a name by passing an
argument, that name is used as the name in Objective-C code and as the
runtime name. If you omit the argument, the name used in Objective-C code
matches the name in Swift code, and the runtime name follows the normal
Swift compiler convention of name mangling.
objcMembers
Apply this attribute to a class declaration, to implicitly apply the objc
attribute to all Objective-C compatible members of the class, its
extensions, its subclasses, and all of the extensions of its subclasses.
Most code should use the objc attribute instead, to expose only the
declarations that are needed. If you need to expose many
declarations, you can group them in an extension that has the objc
attribute. The objcMembers attribute is a convenience for libraries that
make heavy use of the introspection facilities of the Objective-C
runtime. Applying the objc attribute when it isn’t needed can increase
your binary size and adversely affect performance.
propertyWrapper
Apply this attribute to a class, structure, or enumeration declaration to
use that type as a property wrapper. When you apply this attribute to
a type, you create a custom attribute with the same name as the type.
Apply that new attribute to a property of a class, structure, or
enumeration to wrap access to the property through an instance of
the wrapper type; apply the attribute to a local stored variable
declaration to wrap access to the variable the same way. Computed
variables, global variables, and constants can’t use property
wrappers.
resultBuilder
Apply this attribute to a class, structure, enumeration to use that type
as a result builder. A result builder is a type that builds a nested data
structure step by step. You use result builders to implement a
domain-specific language (DSL) for creating nested data structures in
a natural, declarative way. For an example of how to use the
resultBuilder attribute, see Result Builders.
Builds a final result from a partial result. You can implement this
method as part of a result builder that uses a different type for
partial and final results, or to perform other postprocessing on a
result before returning it.
For example, the code below defines a simple result builder that
builds an array of integers. This code defines Component and
Expression as type aliases, to make it easier to match the examples
below to the list of methods above.
Result Transformations
requires_stored_property_inits
Apply this attribute to a class declaration to require all stored
properties within the class to provide default values as part of their
definitions. This attribute is inferred for any class that inherits from
NSManagedObject.
UIApplicationMain
Apply this attribute to a class to indicate that it’s the application
delegate. Using this attribute is equivalent to calling the
UIApplicationMain function and passing this class’s name as the
name of the delegate class.
If you don’t use this attribute, supply a main.swift file with code at the
top level that calls the UIApplicationMain(_:_:_:_:) function. For
example, if your app uses a custom subclass of UIApplication as its
principal class, call the UIApplicationMain(_:_:_:_:) function
instead of using this attribute.
unchecked
Apply this attribute to a protocol type as part of a type declaration’s
list of adopted protocols to turn off enforcement of that protocol’s
requirements.
warn_unqualified_access
Apply this attribute to a top-level function, instance method, or class
or static method to trigger warnings when that function or method is
used without a preceding qualifier, such as a module name, type
name, or instance variable or constant. Use this attribute to help
discourage ambiguity between functions with the same name that are
accessible from the same scope.
Type Attributes
You can apply type attributes to types only.
autoclosure
Apply this attribute to delay the evaluation of an expression by
automatically wrapping that expression in a closure with no
arguments. You apply it to a parameter’s type in a function or method
declaration, for a parameter whose type is a function type that takes
no arguments and that returns a value of the type of the expression.
For an example of how to use the autoclosure attribute, see
Autoclosures and Function Type.
escaping
Apply this attribute to a parameter’s type in a function or method
declaration to indicate that the parameter’s value can be stored for
later execution. This means that the value is allowed to outlive the
lifetime of the call. Function type parameters with the escaping type
attribute require explicit use of self. for properties or methods. For
Sendable
Apply this attribute to the type of a function to indicate that the
function or closure is sendable. Applying this attribute to a function
type has the same meaning as conforming a non–function type to the
Sendable protocol.
unknown
Apply this attribute to a switch case to indicate that it isn’t expected to
be matched by any case of the enumeration that’s known at the time
the code is compiled. For an example of how to use the unknown
attribute, see Switching Over Future Enumeration Cases.
In Swift, there are two basic kinds of patterns: those that successfully
match any kind of value, and those that may fail to match a specified
value at runtime.
The second kind of pattern is used for full pattern matching, where
the values you’re trying to match against may not be there at runtime.
These include enumeration case patterns, optional patterns,
expression patterns, and type-casting patterns. You use these
patterns in a case label of a switch statement, a catch clause of a do
statement, or in the case condition of an if, while, guard, or for-in
statement.
Wildcard Pattern
A wildcard pattern matches and ignores any value and consists of an
underscore (_). Use a wildcard pattern when you don’t care about the
values being matched against. For example, the following code
iterates through the closed range 1...3, ignoring the current value of
the range on each iteration of the loop:
1 for _ in 1...3 {
2 // Do something three times.
3 }
G R A M M A R O F A W I L D C A R D PAT T E R N
wildcard-pattern → _
Identifier Pattern
An identifier pattern matches any value and binds the matched value
to a variable or constant name. For example, in the following constant
let someValue = 42
G R A M M A R O F A N I D E N T I F I E R PAT T E R N
identifier-pattern → identifier
Value-Binding Pattern
A value-binding pattern binds matched values to variable or constant
names. Value-binding patterns that bind a matched value to the name
of a constant begin with the let keyword; those that bind to the name
of variable begin with the var keyword.
G R A M M A R O F A VA L U E - B I N D I N G PAT T E R N
Tuple Pattern
A tuple pattern is a comma-separated list of zero or more patterns,
enclosed in parentheses. Tuple patterns match values of
corresponding tuple types.
You can constrain a tuple pattern to match certain kinds of tuple types
by using type annotations. For example, the tuple pattern (x, y):
(Int, Int) in the constant declaration let (x, y): (Int, Int) =
(1, 2) matches only tuple types in which both elements are of type
Int.
1 let points = [(0, 0), (1, 0), (1, 1), (2, 0), (2,
1)]
2 // This code isn't valid.
3 for (x, 0) in points {
4 /* ... */
5 }
1 let a = 2 // a: Int = 2
2 let (a) = 2 // a: Int = 2
3 let (a): Int = 2 // a: Int = 2
G R A M M A R O F A T U P L E PAT T E R N
G R A M M A R O F A N E N U M E R AT I O N C A S E PAT T E R N
G R A M M A R O F A N O P T I O N A L PAT T E R N
optional-pattern → identifier-pattern ?
Type-Casting Patterns
There are two type-casting patterns, the is pattern and the as
pattern. The is pattern appears only in switch statement case labels.
The is and as patterns have the following form:
is type
pattern as type
G R A M M A R O F A T Y P E C A S T I N G PAT T E R N
Expression Pattern
An expression pattern represents the value of an expression.
Expression patterns appear only in switch statement case labels.
G R A M M A R O F A N E X P R E S S I O N PAT T E R N
expression-pattern → expression
where requirements
You can also specify the requirement that two types be identical,
using the == operator. For example, <S1: Sequence, S2: Sequence>
where S1.Iterator.Element == S2.Iterator.Element expresses the
constraints that S1 and S2 conform to the Sequence protocol and that
the elements of both sequences must be of the same type.
Any type argument substituted for a type parameter must meet all the
constraints and requirements placed on the type parameter.
G R A M M A R O F A G E N E R I C PA R A M E T E R C L A U S E
You can also replace a type parameter with a type argument that’s
itself a specialized version of a generic type (provided it satisfies the
appropriate constraints and requirements). For example, you can
Lexical Structure
G R A M M A R O F W H I T E S PA C E
integer-literal → binary-literal
integer-literal → octal-literal
integer-literal → decimal-literal
integer-literal → hexadecimal-literal
binary-literal → 0b binary-digit binary-literal-characters opt
binary-digit → Digit 0 or 1
binary-literal-character → binary-digit | _
binary-literal-characters → binary-literal-character binary-literal-characters
opt
octal-literal → 0o octal-digit octal-literal-characters opt
octal-digit → Digit 0 through 7
octal-literal-character → octal-digit | _
octal-literal-characters → octal-literal-character octal-literal-characters opt
decimal-literal → decimal-digit decimal-literal-characters opt
decimal-digit → Digit 0 through 9
decimal-digits → decimal-digit decimal-digits opt
decimal-literal-character → decimal-digit | _
decimal-literal-characters → decimal-literal-character decimal-literal-
characters opt
hexadecimal-literal → 0x hexadecimal-digit hexadecimal-literal-characters
opt
hexadecimal-digit → Digit 0 through 9, a through f, or A through F
hexadecimal-literal-character → hexadecimal-digit | _
hexadecimal-literal-characters → hexadecimal-literal-character
hexadecimal-literal-characters opt
regular-expression-literal → regular-expression-literal-opening-delimiter
regular-expression regular-expression-literal-closing-delimiter
regular-expression → Any regular expression
regular-expression-literal-opening-delimiter → extended-regular-expression-
literal-delimiter opt /
regular-expression-literal-closing-delimiter → / extended-regular-
expression-literal-delimiter opt
extended-regular-expression-literal-delimiter → # extended-regular-
expression-literal-delimiter opt
Types
type → function-type
type → array-type
type → dictionary-type
type → type-identifier
type → tuple-type
type → optional-type
type → implicitly-unwrapped-optional-type
type → protocol-composition-type
type → opaque-type
type → metatype-type
type → any-type
type → self-type
type → ( type )
G R A M M A R O F A T Y P E A N N O TAT I O N
G R A M M A R O F A N A R R AY T Y P E
array-type → [ type ]
optional-type → type ?
G R A M M A R O F A N I M P L I C I T LY U N W R A P P E D O P T I O N A L T Y P E
implicitly-unwrapped-optional-type → type !
G R A M M A R O F A N O PA Q U E T Y P E
G R A M M A R O F A M E TAT Y P E T Y P E
any-type → Any
self-type → Self
G R A M M A R O F A T Y P E I N H E R I TA N C E C L A U S E
type-inheritance-clause → : type-inheritance-list
type-inheritance-list → attributes opt type-identifier | attributes opt type-
identifier , type-inheritance-list
Expressions
GRAMMAR OF AN EXPRESSION
await-operator → await
G R A M M A R O F A N A S S I G N M E N T O P E R AT O R
assignment-operator → =
G R A M M A R O F A C O N D I T I O N A L O P E R AT O R
conditional-operator → ? expression :
G R A M M A R O F A T Y P E - C A S T I N G O P E R AT O R
type-casting-operator → is type
type-casting-operator → as type
type-casting-operator → as ? type
type-casting-operator → as ! type
literal-expression → literal
literal-expression → array-literal | dictionary-literal | playground-literal
literal-expression → #file | #fileID | #filePath
literal-expression → #line | #column | #function | #dsohandle
array-literal → [ array-literal-items opt ]
array-literal-items → array-literal-item ,opt | array-literal-item , array-
literal-items
array-literal-item → expression
dictionary-literal → [ dictionary-literal-items ] | [ : ]
dictionary-literal-items → dictionary-literal-item ,opt | dictionary-literal-
item , dictionary-literal-items
dictionary-literal-item → expression : expression
playground-literal → #colorLiteral ( red : expression , green :
expression , blue : expression , alpha : expression )
playground-literal → #fileLiteral ( resourceName : expression )
playground-literal → #imageLiteral ( resourceName : expression )
implicit-member-expression → . identifier
implicit-member-expression → . identifier . postfix-expression
G R A M M A R O F A PA R E N T H E S I Z E D E X P R E S S I O N
parenthesized-expression → ( expression )
wildcard-expression → _
G R A M M A R O F A K E Y- PAT H S T R I N G E X P R E S S I O N
postfix-expression → primary-expression
postfix-expression → postfix-expression postfix-operator
postfix-expression → function-call-expression
postfix-expression → initializer-expression
postfix-expression → explicit-member-expression
postfix-expression → postfix-self-expression
postfix-expression → subscript-expression
postfix-expression → forced-value-expression
postfix-expression → optional-chaining-expression
G R A M M A R O F A F O R C E D - VA L U E E X P R E S S I O N
forced-value-expression → postfix-expression !
optional-chaining-expression → postfix-expression ?
Statements
G R A M M A R O F A S TAT E M E N T
G R A M M A R O F A L O O P S TAT E M E N T
loop-statement → for-in-statement
loop-statement → while-statement
loop-statement → repeat-while-statement
G R A M M A R O F A F O R - I N S TAT E M E N T
G R A M M A R O F A R E P E AT - W H I L E S TAT E M E N T
G R A M M A R O F A B R A N C H S TAT E M E N T
branch-statement → if-statement
branch-statement → guard-statement
branch-statement → switch-statement
G R A M M A R O F A N I F S TAT E M E N T
G R A M M A R O F A G U A R D S TAT E M E N T
G R A M M A R O F A L A B E L E D S TAT E M E N T
G R A M M A R O F A C O N T R O L T R A N S F E R S TAT E M E N T
control-transfer-statement → break-statement
control-transfer-statement → continue-statement
control-transfer-statement → fallthrough-statement
control-transfer-statement → return-statement
control-transfer-statement → throw-statement
G R A M M A R O F A B R E A K S TAT E M E N T
G R A M M A R O F A F A L LT H R O U G H S TAT E M E N T
fallthrough-statement → fallthrough
G R A M M A R O F A R E T U R N S TAT E M E N T
G R A M M A R O F A T H R O W S TAT E M E N T
G R A M M A R O F A D E F E R S TAT E M E N T
G R A M M A R O F A D O S TAT E M E N T
G R A M M A R O F A C O M P I L E R C O N T R O L S TAT E M E N T
compiler-control-statement → conditional-compilation-block
compiler-control-statement → line-control-statement
compiler-control-statement → diagnostic-statement
G R A M M A R O F A L I N E C O N T R O L S TAT E M E N T
G R A M M A R O F A N AVA I L A B I L I T Y C O N D I T I O N
Declarations
declaration → import-declaration
declaration → constant-declaration
declaration → variable-declaration
declaration → typealias-declaration
declaration → function-declaration
declaration → enum-declaration
declaration → struct-declaration
declaration → class-declaration
declaration → actor-declaration
declaration → protocol-declaration
declaration → initializer-declaration
declaration → deinitializer-declaration
declaration → extension-declaration
declaration → subscript-declaration
declaration → operator-declaration
declaration → precedence-group-declaration
declarations → declaration declarations opt
G R A M M A R O F A T O P - L E V E L D E C L A R AT I O N
G R A M M A R O F A N I M P O R T D E C L A R AT I O N
G R A M M A R O F A C O N S TA N T D E C L A R AT I O N
G R A M M A R O F A T Y P E A L I A S D E C L A R AT I O N
G R A M M A R O F A C L A S S D E C L A R AT I O N
G R A M M A R O F A N A C T O R D E C L A R AT I O N
G R A M M A R O F A P R O T O C O L P R O P E R T Y D E C L A R AT I O N
G R A M M A R O F A P R O T O C O L M E T H O D D E C L A R AT I O N
G R A M M A R O F A P R O T O C O L I N I T I A L I Z E R D E C L A R AT I O N
G R A M M A R O F A P R O T O C O L S U B S C R I P T D E C L A R AT I O N
G R A M M A R O F A N I N I T I A L I Z E R D E C L A R AT I O N
G R A M M A R O F A D E I N I T I A L I Z E R D E C L A R AT I O N
G R A M M A R O F A N E X T E N S I O N D E C L A R AT I O N
G R A M M A R O F A N O P E R AT O R D E C L A R AT I O N
G R A M M A R O F A P R E C E D E N C E G R O U P D E C L A R AT I O N
Attributes
G R A M M A R O F A N AT T R I B U T E
Patterns
G R A M M A R O F A W I L D C A R D PAT T E R N
wildcard-pattern → _
G R A M M A R O F A N I D E N T I F I E R PAT T E R N
identifier-pattern → identifier
G R A M M A R O F A VA L U E - B I N D I N G PAT T E R N
G R A M M A R O F A T U P L E PAT T E R N
G R A M M A R O F A N E N U M E R AT I O N C A S E PAT T E R N
G R A M M A R O F A N O P T I O N A L PAT T E R N
optional-pattern → identifier-pattern ?
G R A M M A R O F A T Y P E C A S T I N G PAT T E R N
expression-pattern → expression
2022-09-12
2022-03-14
2021-09-20
2021-04-26
2020-09-16
Added more information about Any and moved it into the new
Any Type section.
2020-03-24
Updated the Self Type section, now that the Self can be used in
more contexts.
2019-09-10
Updated the Self Type section, now that Self can be used to
refer to the type introduced by the current class, structure, or
enumeration declaration.
2019-03-25
2018-09-17
2018-03-29
2017-12-04
2017-09-19
2017-03-27
2016-10-27
Added a note to the Type Casting for Any and AnyObject section
about using an optional value when a value of type Any is
expected.
2016-09-13
2016-03-21
2015-10-20
2015-09-16
2015-04-08
Swift now has a native Set collection type. For more information,
see Sets.
Swift now includes the as? and as! failable downcast operators.
For more information, see Checking for Protocol Conformance.
Type casts that can fail at runtime now use the as? or as!
operator, and type casts that are guaranteed not to fail use the
as operator. For more information, see Type-Casting Operators.
2014-10-16
2014-08-18
Added a note that the start value a for the Range Operators
a...b and a..<b must not be greater than the end value b.
Clarified the full list of characters that can be used when defining
Custom Operators.
nil and the Booleans true and false are now Literals.
Swift’s Array type now has full value semantics. Updated the
information about Mutability of Collections and Arrays to reflect
the new approach. Also clarified the assignment and copy
behavior for strings arrays and dictionaries.
Apple Inc.
Copyright © 2022 Apple Inc.
Apple Inc.
One Apple Park Way
Cupertino, CA 95014
408-996-1010