O'Reilly logo

Swift Essentials by Dr. Alex Blewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required