Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Swift Essentials
  • Table Of Contents Toc
Swift Essentials

Swift Essentials

By : Alex Blewitt
4.8 (4)
close
close
Swift Essentials

Swift Essentials

4.8 (4)
By: Alex Blewitt

Overview of this book

Whether you are a seasoned Objective-C developer or new to the Xcode platform, Swift Essentials will provide you with all you need to know to get started with the language. Prior experience with iOS development is not necessary, but will be helpful to get the most out of the book.
Table of Contents (10 chapters)
close
close
9
Index

Conditional logic

There are two key types of conditional logic in Swift (known as branch statements in the grammar): the if statement and the switch statement. Unlike other languages, the body of the if must be surrounded with braces {}, and if typed in at the interpreter, the opening brace { must be on the same line as the if statement. The literal values true and false can be used as well as other boolean expressions.

If statements

Conditionally unpacking an optional value is so common that a specific Swift pattern has been created to avoid evaluating the expression twice:

var shopping = [ "Milk", "Eggs", "Coffee", "Tea", ]
var costs = [ "Milk":1, "Eggs":2, "Coffee":3, "Tea":4, ]
var cost = 0
if let cm = costs["Milk"] {
.   cost += cm
. }
> cost
$R0: Int = 1

The if block only executes if the optional value exists. The definition of the constant cm only exists for the body of the if block, and does not exist outside that scope. Furthermore, cm is a non-optional type, so it is guaranteed to not be nil.

To execute an alternative block if the item cannot be found, an else block can be used:

> if let cb = costs["Bread"] {
.  cost += cb
. } else {
.  println("Cannot find any Bread")
. }
Cannot find any Bread

Other boolean expressions can include any expression that conforms to the BooleanType protocol, the equality operators == and !=, the identity operators === and !==, as well as the comparison operators <, <=, >, >=. The is type operator provides a test to see whether an element is of a particular type.

Note

The difference between the equality operator and the identity operator is relevant for classes or other reference types. The equality operator asks "Are these two values equivalent to each other?" whereas the identity operator asks "Are these two references equal to each other?"

There is a boolean operator specific to Swift, which is the ~= pattern match operator. Despite the name, this isn't anything to do with regular expressions; rather, it's a way of asking whether a pattern matches a particular value. This is used in the implementation of the switch block, which is covered in the next section.

In addition to the if statement, there is a ternary if expression similar to other languages. After a condition, a question mark (?) is used, followed by an expression to be used if the condition is true, then a colon (:) followed by the false expression:

> var i = 17
i: Int = 17
> i % 2 == 0 ? "Even" : "Odd"
$R0: String = "Odd"

Switch statements

In addition to if/else, Swift also has a switch statement, similar to C and Java's switch. However, it differs in two important ways. Firstly, case statements no longer have a default fall-through behavior (so there are no bugs introduced by missing a break statement) and secondly, the value of the case statements can be expressions instead of values, pattern matching on type and range. At the end of the corresponding case, the evaluation jumps to the end of the switch block, unless the fallthrough keyword is used. If no case statements match, the default statement is executed:

> var position = 21
position: Int = 21
> switch position {
.   case 1: println("First")
.   case 2: println("Second")
.   case 3: println("Third")
.   case 4...20: println("\(position)th")
.   case position where (position % 10) == 1:
.     println("\(position)st")
.   case let p where (p % 10) == 2:
.     println("\(p)nd")
.   case let p where (p % 10) == 3:
.     println("\(p)rd")
.   default: println("\(position)th")
. }
21st

In the preceding example, the expression prints out First, Second, or Third if the position is 1, 2, or 3 respectively. For numbers between 4 and 20 (inclusive), it prints out the position with a th ordinal. Otherwise, for numbers that end with 1, it prints st; for numbers that end with 2, it prints nd; and for numbers that end with 3, it prints rd. For all other numbers, it prints th.

The 4...20 range expression in a case statement represents a pattern. If the value of the expression matches that pattern, then the corresponding statements will be executed:

> 4...10 ~= 4
$R0: Bool = true
> 4...10 ~= 21
$R1: Bool = false

There are two range operators in Swift: an inclusive or closed range, and an exclusive or half-open range. The closed range is specified with three dots; 1...12 will give a list of integers between one and twelve. The half-open range is specified with two dots and a less than operator; so 1..<10 will provide integers from 1 to 9 but exclude 10.

The where clause in the switch block allows an arbitrary expression to be evaluated, provided that the pattern matches. These are evaluated in-order, in the sequence they are in the source file. If a where clause evaluates to true, then the corresponding set of statements will be executed.

The let variable syntax can be used to define a constant that refers to the value in the switch block. This local constant can be used in the where clause or the corresponding statements for that specific case. Alternatively, variables can be used from the surrounding scope.

Note

If multiple case statements need to match the same pattern, they can be separated with commas in the form of an expression list. Alternatively, the fallthrough keyword can be used to allow the same implementation to be used for multiple case statements.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Swift Essentials
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon