About Swift: The Swift Programming Language
About Swift: The Swift Programming Language
NOTE
For prerelease documentation of a future update to the Swift language, see The Swift
Programming Language.
Swift is a new programming language for iOS and OS X apps that builds on the best of C and
Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns
and adds modern features to make programming easier, more flexible, and more fun. Swifts
clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an
opportunity to reimagine how software development works.
Swift has been years in the making. Apple laid the foundation for Swift by advancing our
existing compiler, debugger, and framework infrastructure. We simplified memory
management with Automatic Reference Counting (ARC). Our framework stack, built on the solid
base of Foundation and Cocoa, has been modernized and standardized throughout. Objective-C
itself has evolved to support blocks, collection literals, and modules, enabling framework
adoption of modern language technologies without disruption. Thanks to this groundwork, we
can now introduce a new language for the future of Apple software development.
Swift feels familiar to Objective-C developers. It adopts the readability of Objective-Cs named
parameters and the power of Objective-Cs dynamic object model. It provides seamless access
to existing Cocoa frameworks and mix-and-match interoperability with Objective-C code.
Building from this common ground, Swift introduces many new features and unifies the
procedural and object-oriented portions of the language.
Swift is friendly to new programmers. It is the first industrial-quality systems programming
language that is as expressive and enjoyable as a scripting language. It supports playgrounds, an
innovative feature that allows programmers to experiment with Swift code and see the results
immediately, without the overhead of building and running an app.
Swift combines the best in modern language thinking with wisdom from the wider Apple
engineering culture. The compiler is optimized for performance, and the language is optimized
for development, without compromising on either. Its designed to scale from hello, world to
an entire operating system. All this makes Swift a sound future investment for developers and
for Apple.
Swift is a fantastic way to write iOS and OS X apps, and will continue to evolve with new
features and capabilities. Our goals for Swift are ambitious. We cant wait to see what you
create with it.
A Swift Tour
Tradition suggests that the first program in a new language should print the words Hello,
world! on the screen. In Swift, this can be done in a single line:
println("Hello, world!")
If you have written code in C or Objective-C, this syntax looks familiar to youin Swift, this line
of code is a complete program. You dont need to import a separate library for functionality like
input/output or string handling. Code written at global scope is used as the entry point for the
program, so you dont need a mainfunction. You also dont need to write semicolons at the end
of every statement.
This tour gives you enough information to start writing code in Swift by showing you how to
accomplish a variety of programming tasks. Dont worry if you dont understand something
everything introduced in this tour is explained in detail in the rest of this book.
NOTE
For the best experience, open this chapter as a playground in Xcode. Playgrounds allow you to
edit the code listings and see the result immediately.
Download Playground
Simple Values
Use let to make a constant and var to make a variable. The value of a constant doesnt need to
be known at compile time, but you must assign it a value exactly once. This means you can use
constants to name a value that you determine once but use in many places.
var myVariable = 42
myVariable = 50
let myConstant = 42
A constant or variable must have the same type as the value you want to assign to it. However,
you dont 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 doesnt provide enough information (or if there is no initial value), specify the
type by writing it after the variable, separated by a colon.
let implicitInteger = 70
let width = 94
let apples = 3
let oranges = 5
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
shoppingList = []
occupations = [:]
Control Flow
Use if and switch to make conditionals, and use for-in, for, while, and do-while to make loops.
Parentheses around the condition or loop variable are optional. Braces around the body are
required.
var teamScore = 0
if score > 50 {
teamScore += 3
} else {
teamScore += 1
teamScore
NOTE
In the code above, teamScore is written on a line by itself. This is a simple way to see the value
of a variable inside a playground.
In an if statement, the conditional must be a Boolean expressionthis means that code such
as if score { ... } is an error, not an implicit comparison to zero.
You can use if and let together to work with values that might be missing. These values are
represented as optionals. An optional value either contains a value or contains nil to indicate
that the value is missing. Write a question mark (?) after the type of a value to mark the value
as optional.
optionalString == nil
}
EXPERIMENT
Change optionalName to nil. What greeting do you get? Add an else clause that sets a different
greeting ifoptionalName 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.
Switches support any kind of data and a wide variety of comparison operationsthey arent
limited to integers and tests for equality.
switch vegetable {
case "celery":
default:
}
EXPERIMENT
Try removing the default case. What error do you get?
Notice how let can be used in a pattern to assign the value that matched that part of a pattern
to a constant.
After executing the code inside the switch case that matched, the program exits from the
switch statement. Execution doesnt continue to the next case, so there is no need to explicitly
break out of the switch at the end of each cases code.
You use for-in to iterate over items in a dictionary by providing a pair of names to use for each
key-value pair. Dictionaries are an unordered collection, so their keys and values are iterated
over in an arbitrary order.
let interestingNumbers = [
var largest = 0
largest = number
largest
EXPERIMENT
Add another variable to keep track of which kind of number was the largest, as well as what
that largest number was.
Use while to repeat a block of code until a condition changes. The condition of a loop can be at
the end instead, ensuring that the loop is run at least once.
var n = 2
n=n*2
var m = 2
do {
m=m*2
m
You can keep an index in a loopeither by using ..< to make a range of indexes or by writing an
explicit initialization, condition, and increment. These two loops do the same thing:
var firstForLoop = 0
for i in 0..<4 {
firstForLoop += i
firstForLoop
var secondForLoop = 0
secondForLoop += i
secondForLoop
Use ..< to make a range that omits its upper value, and use ... to make a range that includes
both values.
Functions and Closures
Use func to declare a function. Call a function by following its name with a list of arguments in
parentheses. Use -> to separate the parameter names and types from the functions return
type.
greet("Bob", "Tuesday")
EXPERIMENT
Remove the day parameter. Add a parameter to include todays lunch special in the greeting.
Use a tuple to make a compound valuefor example, to return multiple values from a function.
The elements of a tuple can be referred to either by name or by number.
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var sum = 0
max = score
min = score
sum += score
statistics.sum
statistics.2
Functions can also take a variable number of arguments, collecting them into an array.
var sum = 0
sum += number
return sum
sumOf()
var y = 10
func add() {
y += 5
add()
return y
returnFifteen()
Functions are a first-class type. This means that a function can return another function as its
value.
return 1 + number
return addOne
increment(7)
if condition(item) {
return true
return false
hasAnyMatches(numbers, lessThanTen)
Functions are actually a special case of closures: blocks of code that can be called later. The
code in a closure has access to things like variables and functions that were available in the
scope where the closure was created, even if the closure is in a different scope when it is
executedyou saw an example of this already with nested functions. You can write a closure
without a name by surrounding code with braces ({}). Use in to separate the arguments and
return type from the body.
numbers.map({
return result
})
EXPERIMENT
Rewrite the closure to return zero for all odd numbers.
You have several options for writing closures more concisely. When a closures 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.
mappedNumbers
You can refer to parameters by number instead of by namethis approach is especially useful
in very short closures. A closure passed as the last argument to a function can appear
immediately after the parentheses.
sortedNumbers
Objects and Classes
Use class followed by the classs name to create a class. A property declaration in a class is
written the same way as a constant or variable declaration, except that it is in the context of a
class. Likewise, method and function declarations are written the same way.
class Shape {
var numberOfSides = 0
}
EXPERIMENT
Add a constant property with let, and add another method that takes an argument.
Create an instance of a class by putting parentheses after the class name. Use dot syntax to
access the properties and methods of the instance.
shape.numberOfSides = 7
class NamedShape {
init(name: String) {
self.name = name
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 assignedeither in its declaration (as
with numberOfSides) or in the initializer (as withname).
Use deinit to create a deinitializer if you need to perform some cleanup before the object is
deallocated.
Subclasses include their superclass name after their class name, separated by a colon. There is
no requirement for classes to subclass any standard root class, so you can include or omit a
superclass as needed.
Methods on a subclass that override the superclasss implementation are marked
with overrideoverriding a method by accident, without override, is detected by the compiler
as an error. The compiler also detects methods with override that dont actually override any
method in the superclass.
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
test.area()
test.simpleDescription()
EXPERIMENT
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 addition to simple properties that are stored, properties can have a getter and a setter.
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
get {
set {
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength
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:
1. Setting the value of properties that the subclass declares.
2. Calling the superclasss initializer.
3. Changing the value of properties defined by the superclass. Any additional setup work that
uses methods, getters, or setters can also be done at this point.
If you dont need to compute the property but still need to provide code that is run before and
after setting a new value, use willSet and didSet. For example, the class below ensures that the
side length of its triangle is always the same as the side length of its square.
class TriangleAndSquare {
willSet {
square.sideLength = newValue.sideLength
willSet {
triangle.sideLength = newValue.sideLength
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.triangle.sideLength
Methods on classes have one important difference from functions. Parameter names in
functions are used only within the function, but parameters names in methods are also used
when you call the method (except for the first parameter). By default, a method has the same
name for its parameters when you call it and within the method itself. You can specify a second
name, which is used inside the method.
class Counter {
counter.incrementBy(2, numberOfTimes: 7)
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.
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.toRaw())
}
The member values of an enumeration are actual values, not just another way of writing their
raw values. In fact, in cases where there isnt a meaningful raw value, you dont have to provide
one.
enum Suit {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
Notice the two ways that the Hearts member of the enumeration is referred to above: When
assigning a value to the hearts constant, the enumeration member Suit.Hearts is referred to by
its full name because the constant doesnt have an explicit type specified. Inside the switch, the
enumeration is referred to by the abbreviated form .Hearts because the value of self is already
known to be a suit. You can use the abbreviated form anytime the values type is already
known.
Use struct to create a structure. Structures support many of the same behaviors as classes,
including methods and initializers. One of the most important differences between structures
and classes is that structures are always copied when they are passed around in your code, but
classes are passed by reference.
struct Card {
enum ServerResponse {
case Error(String)
switch success {
}
EXPERIMENT
Add a third case to ServerResponse and to the switch.
Notice how the sunrise and sunset times are extracted from the ServerResponse value as part
of matching the value against the switch cases.
Protocols and Extensions
Use protocol to declare a protocol.
protocol ExampleProtocol {
}
Classes, enumerations, and structs can all adopt protocols.
func adjust() {
var a = SimpleClass()
a.adjust()
var b = SimpleStructure()
b.adjust()
self += 42
7.simpleDescription
EXPERIMENT
Write an extension for the Double type that adds an absoluteValue property.
You can use a protocol name just like any other named typefor 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
are not available.
protocolValue.simpleDescription
Generics
Write a name inside angle brackets to make a generic function or type.
for i in 0..<times {
result.append(item)
return result
repeat("knock", 4)
You can make generic forms of functions and methods, as well as classes, enumerations, and
structures.
enum OptionalValue<T> {
case None
case Some(T)
possibleInteger = .Some(100)
Use where after the type name to specify a list of requirementsfor example, to require the
type to implement a protocol, to require two types to be the same, or to require a class to have
a particular superclass.
if lhsItem == rhsItem {
return true
return false
The Basics
On This Page
Swift is a new programming language for iOS and OS X app development. Nonetheless, many
parts of Swift will be familiar from your experience of developing in C and Objective-C.
Swift provides its own versions of all fundamental C and Objective-C types, including Int for
integers, Doubleand Float for floating-point values, Bool for Boolean values, and String for
textual data. Swift also provides powerful versions of the two primary collection
types, Array and Dictionary, as described in Collection Types.
Like C, Swift uses variables to store and refer to values by an identifying name. Swift also makes
extensive use of variables whose values cannot be changed. These are known as constants, and
are much more powerful than constants in C. Constants are used throughout Swift to make
code safer and clearer in intent when you work with values that do not need to change.
In addition to familiar types, Swift introduces advanced types not found in Objective-C, such as
tuples. Tuples enable you to create and pass around groupings of values. You can use a tuple to
return multiple values from a function as a single compound value.
Swift also introduces optional types, which handle the absence of a value. Optionals say either
there is a value, and it equals x or there isnt a value at all. Optionals are similar to
using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are
safer and more expressive than nilpointers in Objective-C and are at the heart of many of
Swifts most powerful features.
Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be
clear about the types of values your code can work with. If part of your code expects a String,
type safety prevents you from passing it an Int by mistake. This restriction enables you to catch
and fix errors as early as possible in the development process.
Constants and Variables
Constants and variables associate a name (such
as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a particular type
(such as the number 10 or the string "Hello"). The value of a constant cannot be changed once
it is set, whereas a variable can be set to a different value in the future.
Declaring Constants and Variables
Constants and variables must be declared before they are used. You declare constants with
the let keyword and variables with the var keyword. Heres an example of how constants and
variables can be used to track the number of login attempts a user has made:
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
This code can be read as:
Declare a new constant called maximumNumberOfLoginAttempts, and give it a value of 10.
Then, declare a new variable called currentLoginAttempt, and give it an initial value of 0.
In this example, the maximum number of allowed login attempts is declared as a constant,
because the maximum value never changes. The current login attempt counter is declared as a
variable, because this value must be incremented after each failed login attempt.
You can declare multiple constants or multiple variables on a single line, separated by commas:
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 is 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 is 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.
Naming Constants and Variables
Constant and variable names can contain almost any character, including Unicode characters:
let = 3.14159
let = ""
let = "dogcow"
Constant and variable names cannot contain whitespace characters, mathematical symbols,
arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor
can they begin with a number, although numbers may be included elsewhere within the name.
Once youve declared a constant or variable of a certain type, you cant redeclare it again with
the same name, or change it to store values of a different type. Nor can you change a constant
into a variable or a variable into a constant.
NOTE
If you need to give a constant or variable the same name as a reserved Swift keyword, surround
the keyword with back ticks (`) when using it as a name. However, avoid using keywords as
names unless you have absolutely no choice.
You can change the value of an existing variable to another value of a compatible type. In this
example, the value of friendlyWelcome is changed from "Hello!" to "Bonjour!":
friendlyWelcome = "Bonjour!"
languageName = "Swift++"
println(friendlyWelcome)
// prints "Bonjour!"
println is a global function that prints a value, followed by a line break, to an appropriate
output. In Xcode, for example, println prints its output in Xcodes console pane. (A second
function, print, performs the same task without appending a line break to the end of the value
to be printed.)
The println function prints any String value you pass to it:
println("This is a string")
// this is a comment
Multiline comments start with a forward-slash followed by an asterisk (/*) and end with an
asterisk followed by a forward-slash (*/):
// prints ""
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 typeInt32. 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:
Type inference is particularly useful when you declare a constant or variable with an initial
value. This is often done by assigning a literal value (or literal) to the constant or variable at the
point that you declare it. (A literal value is a value that appears directly in your source code,
such as 42 and 3.14159 in the examples below.)
For example, if you assign a literal value of 42 to a new constant without saying what type it is,
Swift infers that you want the constant to be an Int, because you have initialized it with a
number that looks like an integer:
let meaningOfLife = 42
let pi = 3.14159
let decimalInteger = 17
// UInt8 cannot store negative numbers, and so this will report an error
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.
To convert one specific number type to another, you initialize a new number of the desired
type with the existing value. In the example below, the constant twoThousand is of type UInt16,
whereas the constant one is of type UInt8. They cannot be added together directly, because
they are not of the same type. Instead, this example calls UInt16(one) to create a
new UInt16 initialized with the value of one, and uses this value in place of the original:
let three = 3
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 do not have an explicit type in and of themselves. Their type is inferred only at
the point that they are evaluated by the compiler.
Type Aliases
Type aliases define an alternative name for an existing type. You define type aliases with
the typealiaskeyword.
Type aliases are useful when you want to refer to an existing type by a name that is
contextually more appropriate, such as when working with data of a specific size from an
external source:
// maxAmplitudeFound is now 0
Here, AudioSample is defined as an alias for UInt16. Because it is an alias, the call
to AudioSample.min actually calls UInt16.min, which provides an initial value of 0 for
the maxAmplitudeFound variable.
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:
if turnipsAreDelicious {
} else {
Swifts type safety prevents non-Boolean values from being substituted for Bool. The following
example reports a compile-time error:
let i = 1
if i {
}
However, the alternative example below is valid:
let i = 1
if i == 1 {
}
The result of the i == 1 comparison is of type Bool, and so this second example passes the typecheck. Comparisons like i == 1 are discussed in Basic Operators.
As with other examples of type safety in Swift, this approach avoids accidental errors and
ensures that the intention of a particular section of code is always clear.
Tuples
Tuples group multiple values into a single compound value. The values within a tuple can be of
any type and do not have to be of the same type as each other.
In this example, (404, "Not Found") is a tuple that describes an HTTP status code. An HTTP
status code is a special value returned by a web server whenever you request a web page. A
status code of 404 Not Found is returned if you request a webpage that doesnt exist.
If you only need some of the tuples values, ignore parts of the tuple with an underscore (_)
when you decompose the tuple:
The concept of optionals doesnt exist in C or Objective-C. The nearest thing in Objective-C is
the ability to return nil from a method that would otherwise return an object, with nil meaning
the absence of a valid object. However, this only works for objectsit doesnt work for
structures, basic C types, or enumeration values. For these types, Objective-C methods typically
return a special value (such as NSNotFound) to indicate the absence of a value. This approach
assumes that the methods caller knows there is a special value to test against and remembers
to check for it. Swifts optionals let you indicate the absence of a value for any type at all,
without the need for special constants.
Heres an example of how optionals can be used to cope with the absence of a value.
Swifts String type has a method called toInt, which tries to convert a String value into
an Int value. However, not every string can be converted into an integer. The string "123" can
be converted into the numeric value 123, but the string"hello, world" does not have an obvious
numeric value to convert to.
The example below uses the toInt method to try to convert a String into an Int:
serverResponseCode = nil
Swifts nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a nonexistent
object. In Swift, nil is not a pointerit is the absence of a value of a certain type. Optionals
of any type can be set tonil, not just object types.
If Statements and Forced Unwrapping
You can use an if statement to find out whether an optional contains a value by comparing the
optional against nil. You perform this comparison with the equal to operator (==) or the not
equal to operator (!=).
If an optional has a value, it is considered to be not equal to nil:
if convertedNumber != nil {
if convertedNumber != nil {
} else {
if assumedString != nil {
println(assumedString)
println(definiteString)
let age = -3
assert(age >= 0)
When to Use Assertions
Use an assertion whenever a condition has the potential to be false, but must definitely be true
in order for your code to continue execution. Suitable scenarios for an assertion check include:
An integer subscript index is passed to a custom subscript implementation, but the
subscript index value could be too low or too high.
A value is passed to a function, but an invalid value means that the function cannot fulfill its
task.
An optional value is currently nil, but a non-nil value is essential for subsequent code to
execute successfully.
See also Subscripts and Functions.
NOTE
Assertions cause your app to terminate and are not a substitute for designing your code in such
a way that invalid conditions are unlikely to arise. Nonetheless, in situations where invalid
conditions are possible, an assertion is an effective way to ensure that such conditions are
highlighted and noticed during development, before your app is published.
Basic Operators
On This Page
An operator is a special symbol or phrase that you use to check, change, or combine values. For
example, the addition operator (+) adds two numbers together (as in let i = 1 + 2). More
complex examples include the logical AND operator && (as in if enteredDoorCode &&
passedRetinaScan) and the increment operator ++i, which is a shortcut to increase the value
of i by 1.
Swift supports most standard C operators and improves several capabilities to eliminate
common coding errors. The assignment operator (=) does not 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 Swifts overflow operators,
as described in Overflow Operators.
Unlike C, Swift lets you perform remainder (%) calculations on floating-point numbers. Swift
also provides two range operators (a..<b and a...b) not found in C, as a shortcut for expressing a
range of values.
This chapter describes the common operators in Swift. Advanced Operators covers Swifts
advanced operators, and describes how to define your own custom operators and implement
the standard operators for your own custom types.
Terminology
Operators are unary, binary, or ternary:
Unary operators operate on a single target (such as -a). Unary prefix operators appear
immediately before their target (such as !b), and unary postfix operators appear
immediately after their target (such as i++).
Binary operators operate on two targets (such as 2 + 3) and are infix because they appear in
between their two targets.
Ternary operators operate on three targets. Like C, Swift has only one ternary operator, the
ternary conditional operator (a ? b : c).
The values that operators affect are operands. In the expression 1 + 2, the + symbol is a binary
operator and its two operands are the values 1 and 2.
Assignment Operator
The assignment operator (a = b) initializes or updates the value of a with the value of b:
let b = 10
var a = 5
a=b
// 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:
if x = y {
}
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 (/)
1 + 2 // equals 3
5 - 3 // equals 2
2 * 3 // equals 6
Remainder Operator
The remainder operator (a % b) works out how many multiples of b will fit inside a and returns
the value that is left over (known as the remainder).
NOTE
The remainder operator (%) is also known as a modulo operator in other languages. However,
its behavior in Swift for negative numbers means that it is, strictly speaking, a remainder rather
than a modulo operation.
Heres how the remainder operator works. To calculate 9 % 4, you first work out how many 4s
will fit inside 9:
You can fit two 4s inside 9, and the remainder is 1 (shown in orange).
In Swift, this would be written as:
9 % 4 // equals 1
To determine the answer for a % b, the % operator calculates the following equation and
returns remainder as its output:
a = (b some multiplier) + remainder
where some multiplier is the largest number of multiples of b that will fit inside a.
Inserting 9 and 4 into this equation yields:
9 = (4 2) + 1
The same method is applied when calculating the remainder for a negative value of a:
-9 % 4 // equals -1
Inserting -9 and 4 into the equation yields:
-9 = (4 -2) + -1
giving a remainder value of -1.
The sign of b is ignored for negative values of b. This means that a % b and a % -b always give
the same answer.
Floating-Point Remainder Calculations
Unlike the remainder operator in C and Objective-C, Swifts remainder operator can also
operate on floating-point numbers:
var i = 0
var a = 0
let b = ++a
let c = a++
let three = 3
The unary minus operator (-) is prepended directly before the value it operates on, without any
white space.
Unary Plus Operator
The unary plus operator (+) simply returns the value it operates on, without any change:
let minusSix = -6
var a = 1
a += 2
// a is now equal to 3
The expression a += 2 is shorthand for a = a + 2. Effectively, the addition and the assignment are
combined into one operator that performs both tasks at the same time.
NOTE
The compound assignment operators do not return a value. You cannot write let b = a += 2, for
example. This behavior is different from the increment and decrement operators mentioned
above.
A complete list of compound assignment operators can be found in Expressions.
Comparison Operators
Swift supports all standard C comparison operators:
Equal to (a == b)
Not equal to (a != b)
Greater than (a > b)
Less than (a < b)
Greater than or equal to (a >= b)
Less than or equal to (a <= b)
NOTE
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 Classes and
Structures.
Each of the comparison operators returns a Bool value to indicate whether or not the
statement is true:
if name == "world" {
println("hello, world")
} else {
if question {
answer1
} else {
answer2
}
Heres 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
doesnt have a header:
let contentHeight = 40
// rowHeight is equal to 90
The preceding example is shorthand for the code below:
let contentHeight = 40
if hasHeader {
rowHeight = rowHeight + 50
} else {
rowHeight = rowHeight + 20
// rowHeight is equal to 90
The first examples use of the ternary conditional operator means that rowHeight can be set to
the correct value on a single line of code. This is more concise than the second example, and
removes the need forrowHeight to be a variable, because its value does not need to be
modified within an if statement.
The ternary conditional operator provides an efficient shorthand for deciding which of two
expressions to consider. Use the ternary conditional operator with care, however. Its
conciseness can lead to hard-to-read code if overused. Avoid combining multiple instances of
the ternary conditional operator into one compound statement.
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 ais nil. The expression a is always of an optional type. The expression b must
match the type that is stored inside a.
The nil coalescing operator is shorthand for the code below:
a != nil ? a! : b
The code above uses the ternary conditional operator and forced unwrapping (a!) to access the
value wrapped inside a when a is not 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
If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit
evaluation.
The example below uses the nil coalescing operator to choose between a default color name
and an optional user-defined color name:
userDefinedColorName = "green"
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
For more on for-in loops, see Control Flow.
Half-Open Range Operator
The half-open range operator (a..<b) defines a range that runs from a to b, but does not
include b. It is said to be half-open because it contains its first value, but not its final value. As
with the closed range operator, the value of a must not be greater than b.
Half-open ranges are particularly useful when you work with zero-based lists such as arrays,
where it is useful to count up to (but not including) the length of the list:
for i in 0..<count {
if !allowedEntry {
println("ACCESS DENIED")
If either value is false, the overall expression will also be false. In fact, if the first value is false,
the second value wont even be evaluated, because it cant possibly make the overall
expression equate to true. This is known as short-circuit evaluation.
This example considers two Bool values and only allows access if both values are true:
println("Welcome!")
} else {
println("ACCESS DENIED")
if hasDoorKey || knowsOverridePassword {
println("Welcome!")
} else {
println("ACCESS DENIED")
// prints "Welcome!"
Combining Logical Operators
You can combine multiple logical operators to create longer compound expressions:
println("Welcome!")
} else {
println("ACCESS DENIED")
// prints "Welcome!"
This example uses multiple && and || operators to create a longer compound expression.
However, the && and|| operators still operate on only two values, so this is actually three
smaller expressions chained together. The example can be read as:
If weve 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 password, then allow access.
Based on the values of enteredDoorCode, passedRetinaScan, and hasDoorKey, the first two
mini-expressions arefalse. However, the emergency override password is known, so the overall
compound expression still evaluates to true.
Explicit Parentheses
It is sometimes useful to include parentheses when they are not strictly needed, to make the
intention of a complex expression easier to read. In the door access example above, it is useful
to add parentheses around the first part of the compound expression to make its intent explicit:
println("Welcome!")
} else {
println("ACCESS DENIED")
// prints "Welcome!"
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 doesnt change, but
the overall intention is clearer to the reader. Readability is always preferred over brevity; use
parentheses where they help to make your intentions clear.
The Basics
Strings and Characters
Copyright 2014 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated:
2014-09-17
String Literals
You can include predefined String values within your code as string
literals. A string literal is a fixed sequence of textual characters
surrounded by a pair of double quotes ("").
Use a string literal as an initial value for a constant or variable:
let someString = "Some string literal value"
For information about using special characters in string literals, see Special Unicode
Characters in String Literals.
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 cannot be modified):
var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"
This behavior differs from that of NSString in Cocoa. When you create
an NSString instance in Cocoa, and pass it to a function or method or assign it
to a variable, you are always passing or assigning a reference to the same
single NSString. No copying of the string takes place, unless you specifically
request it.
Swifts copy-by-default String behavior ensures that when a
function or method passes you a String value, it is clear that you
own that exact String value, regardless of where it came from. You
can be confident that the string you are passed will not be modified
unless you modify it yourself.
Behind the scenes, Swifts compiler optimizes string usage so that
actual copying takes place only when absolutely necessary. This
means you always get great performance when working with strings
as value types.
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. Each item that you insert into the string
literal is wrapped in a pair of parentheses, prefixed by a backslash:
String interpolation
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
NOTE
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.
Swifts Stringand Character types are fully Unicode-compliant,
as described in this section.
Unicode
Unicode Scalars
Behind the scenes, Swifts native String type is built from Unicode
scalar values. A Unicode scalar is a unique 21-bit number for a
character or modifier, such as U+0061 for LATIN SMALL LETTER
A ("a"), or U+1F425 for FRONT-FACING BABY CHICK ("").
NOTE
Note that not all 21-bit Unicode scalars are assigned to a character
some scalars are reserved for future assignment. Scalars that have
been assigned to a character typically also have a name, such
as LATIN SMALL LETTER A and FRONT-FACING BABY CHICK in
the examples above.
The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line
feed), \r(carriage return), \" (double quote) and \' (single quote)
An arbitrary Unicode scalar, written as \u{n}, where n is between one and eight hexadecimal digits
Counting Characters
To retrieve a count of the Character values in a string, call the
global countElements function and pass in a string as the
functions sole parameter:
let unusualMenagerie = "Koala , Snail , Penguin , Dromedary "
println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
is 4"
NOTE
Comparing Strings
Swift provides three ways to compare textual values: string and
character equality, prefix equality, and suffix equality.
if eAcuteQuestion == combinedEAcuteQuestion {
println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
if latinCapitalLetterA != cyrillicCapitalLetterA {
println("These two characters are not equivalent")
}
// prints "These two characters are not equivalent"
NOTE
A collection of UTF-8 code units (accessed with the strings utf8 property)
A collection of UTF-16 code units (accessed with the strings utf16 property)
A collection of 21-bit Unicode scalar values, equivalent to the strings UTF-32 encoding form (accessed
with the strings unicodeScalars property)
D g"
UTF-8 Representation
You can access a UTF-8 representation of a String by iterating
over its utf8 property. This property is of typeString.UTF8View,
which is a collection of unsigned 8-bit (UInt8) values, one for each
byte in the strings UTF-8 representation:
for codeUnit in dogString.utf8 {
print("\(codeUnit) ")
}
print("\n")
// 68 111 103 226 128 188 240 159 144 182
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 strings UTF16 representation:
for codeUnit in dogString.utf16 {
print("\(codeUnit) ")
}
print("\n")
// 68 111 103 8252 55357 56374
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 strings UTF-8 representation (because these
Unicode scalars represent ASCII characters).
The fourth codeUnit value (8252) is a decimal equivalent of the
hexadecimal value 203C, which represents the Unicode
scalar U+203C for the DOUBLE EXCLAMATION MARK character. This
character can be represented as a single code unit in UTF-16.
The fifth and sixth codeUnit values (55357 and 56374) are a UTF16 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).
Basic Operators
Collection Types
Copyright 2014 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated: 2014-09-17