• Waqar Malik


Expressions are the building blocks of any program. Values, variables, constants, and functions are combined to form expressions, which, in turn, are combined to form a program. When the program is executed, expressions are interpreted according to the rules set by the particular language. These rules can include precedence and associativity, and they produce results and possibly a new state for the program.


Return Type Runtime Error Assignment Operator Binary Expression Optional Type 
These keywords were added by machine and not by the authors. This process is experimental and the keywords may be updated as the learning algorithm improves.

Expressions are the building blocks of any program. Values, variables, constants, and functions are combined to form expressions, which, in turn, are combined to form a program. When the program is executed, expressions are interpreted according to the rules set by the particular language. These rules can include precedence and associativity, and they produce results and possibly a new state for the program.

Swift is no different. It provides four types of expressions:
  • Primary

  • Prefix

  • Binary

  • Postfix

Evaluating expressions in Swift produces a result, a side effect, or both. There are some expressions that require more information. We will take a look at these and expand on their features and requirements.


An expression is said to have a side effect if it modifies some state or has an observable interaction beyond the value of the expression.

Primary Expressions

Primary expressions are the simplest of the expressions. They provide access to values such as x, “This”, 4.5, and so forth. These expressions are used in combination with operators to form compound expressions. Some are literal expressions, such as a string literal or a number literal. Other literal expressions are dictionaries and arrays, and the following built-in literals:
  • __FILE__ is the name of the file that uses it, and it’s a string.

  • __LINE__ is the number of the line where it appears, and it’s an Int.

  • __COLUMN__is the number of the column where it appears, and it’s an Int.

  • __FUNCTION__ is the name of the declaration in which it’s used, and it’s a String.


A prefix expression, as the name implies, adds an operator to the beginning of a given expression. Prefix operators take one argument and have the general form:

prefix-operator right-hand-side




Try Operator

The latest release of the language introduces a try operator. The try operator is applied to an expression that can produce and error. The general form is:

try expression

There is also an optional-try expression which when executed; if the error producing expression produces an error the value of the try? result is nil other wise the valid result from the expression is produced

var myResult = try? someErrorProducingFuction()

The value of myResult will be an optional value if the function does not produce any error, the result of the function will be assigned to myResult. If the function produces an error then nil value will be assigned.

The third variant of the try expression is a forced-try expression which has the same effect as force unboxing.

try! someErrorProducingFunction()

If the function does not produce an error then the value of the result from function is returned if the function produces and error then there is a runtime error and may cuase a crash in your code.

When the try operator is applied it applies a the who exression to it right side if there is a complex exession then it applies the who expression.

try someErrorProducingFunction + someOtherErrorProducingFuction()

In this case the scope of the try is both functions is similar to writing

(try someErrorProducingFunction + someOtherErrorProducingFuction())

If you want reduce the scope and apply to the first fuction then we would write it as

(try someErrorProducingFunction() ) + someOtherErrorProducingFunction()

Try Does not apply to anything to the left hand side of the expression, except when taking the result from the try.


A postfix expression is where the operator is at the end. In Swift you have two-postfix expression:
  • ++ increment

  • -- decrement

To use thse you simply add them at the end of the number. 3++ or 3—


Technically, all primary expression are also postfix expressions.


Binary expressions are the most common expressions in most languages. They take an argument on the left-hand side (lhs), then an infix operator, and another argument on the right-hand side (rhs). The arguments can be either an expression or an instance of a type, depending on the operator.

left-hand-side infix-operator right-hand-side

Swift provides a very rich set of binary operators, the most common of these binary expression is the assignment expression using the = operator.

Assignment Operator

The general form of the assignment operator is:

left-hand-side = right-hand-side

The left hand side is an expression that will be assigned the value(s) from the right hand side expression. The lhs can be a simple value or a compound, such as a structure, a tuple, or an enumeration type. What’s new in Swift is the tuple assignment—you can assign multiple values using a tuple. The one requirement is that the lhs tuple and the rhs tuple have the same structure. Here are some valid tuple assignments:

(a, b) = (4, 6.5)

(lastName, firstName, middleName) = ("Babbage", "Charles", nil)

(a, _, b, (c, d), x) = (5.0, "Hello", (6, "yellow"), "Apple")

If you want to ignore a value during an assignment, use the _ (underscore) in place of that part of the expression. In the third example, the value “Hello” is being ignored during the assignment.

Here are some invalid tuple assignments:

(a, b)= 5

(a, b) = (5)

(a, (b, c)) = (1, 2, 3)

Ternary Conditional

There’s another infix operator that’s not binary. It’s called the ternary conditional operator and it requires three items. The operator looks like this ?: and works like an if-else statement but condensed to one line.

if condition {

        evaluate true

} else {

        evaluate false


With the ternary operator, you can rewrite that code as:

condition ? evaluate true : evaluate false

If-else statements don’t return a value, but the ternary operation returns the value of the expression evaluated.

Casting Operators

Swift provides three operators to use when downcasting or introspection types.
  • is, to check if the type is of a specific type.

  • as, to downcast the type to another type.

  • as?, to downcast as an optional type.

  • as!, to downcase an a forced unboxed type.

To check whether a type can be converted, simply use expression is type. The expression will return true if the expression evaluates to type, or false if expression doesn’t evaluate to type.

The general form of these expressions is:
  • Expression is Type

  • Expression as Type

  • Expression as? Type

  • Expression as! Type

To actually downcast the value, you can use as, as? or as!. The first one is if the type is known at the compile time and known that will always succeed. With the second, if the downcast succeeds, it’s wrapped in an optional. If it fails, the value is nil. The last one is forced cast if the cast fails then there is a runtime error, otherwise the valid valid is assigned.

If the compiler knows at compile time that a type can’t be cast, that results in a compile-time error. In Cocoa Touch frameworks you can always downcast to NSObject because all objects have the same root class. But in Swift, that’s not the case, so if the class is not a subclass of another, casting isn’t possible and the compiler will give an error.

Self and Super

There are two special expression types called self and super.

If used within the class function, the self expression refers to the type itself, but in an instance method it refers to a specific instance of that type. Self can be used in various forms:





One special case is in mutating structures where you can assign a new value to self.

Super is used when referring to a superclass. If the type has a superclass, the form is as follows:




You can also use self as a postfix expression to get the name of the type.



The first example returns the instance of the expression: A.self just refers to a. The second one returns the type.

Closures and Functions

You already know that functions are just named closures, but the syntax is different and takes getting used to.


There are various ways the clousers are used in the swift and can be declared in various formats. Since the closures are first class citizens, you can create variables and then pass that variable around the program, to declare a closure as a variable

var myClosureVariable : (parameters) -> (returnType)

It is similar to defining a variable such as var x : Int, we have not assigned any value to it, they variable can be optional or unboxed optional

var myClosureVaraible : (string : String?) -> (String)

var myClosureVaraible2 : ((string : String?) -> (String))?

var myClosureVariable3 : ((string : String?) -> (String))!

All of the above variables of the the same type because they take same argument type and return the same type we can now defined an alias for this clouse and use that instead of typing the arguments and return types everytime, use the keyword typealias newType = exitingType

typealias MyClosureType = (string : String?) -> (String)

Now we can use this new type to define variables

var myClosureVaraible4 : MyClosureType

Now that you have a variable defined lets assign an actual value to this variable. The general syntax is:

{[captured variables] (closure arguments) -> return-type in



myClosureVaraible4 = { (string : String?) -> String in

    return string ?? ""


If you don’t have arguments or a return type, these can be inferred. There are special forms of closures. Here are rules you can apply to make your closure as verbose or terse as you’d like.
  • A closure can omit the types of its arguments.

  • A closure can omit its return type.

  • If you omit both the argument types and names, omit the in keyword before the statements.

  • If you omit the argument list, the arguments are explicitly named $0, $1, ….

  • If the closure has only a single expression in the body, this implies that the closure returns the value of the expression; the return statement can be omitted.

Here are some examples; these are all equivalent:

{ (a : Int, b : Int) -> Int in

    return a % b


{ (a, b) in

    return a % b


{ return $0 % %1 }

{ $0 % %1 }

If you use a reference type within the closure, you’ll be capturing the variable strongly, as discussed in  Chapter 14.

If you specify a capture list, you have to specify the in keyword in the closure.

{ self.type-member } // strong reference to self

{ [weak self] in self!.type-member } // weak reference to self

{ [unowned self] in self.type-member } // unowned reference

{ [weak weakSelf = self] in weakSelf!.type-member }

Function Calls

To call a function, the syntax is the name of the function followed by a list of arguments in parentheses separated by commas:

function-name(argument1, argument2)

If the function call requires argument names, you add the argument names before each argument, separated by a colon:

function-name(argumentName1 : argument1, argumentName2 : argument2)

There’s a special case where, if the function has a trailing closure (a final argument is a closure), you can move the closure out from the argument list and add it to the end of the function call:

function-name(argument1, {closure})

function-name(argument1) {closure}

Both of these statements are equivalent. If the closure is the only argument, you can even skip the parentheses



There’s also a special initializer function called init:


You can’t use the init functions to initialize variables since they don’t return any value:

var result = type.classFunction //correct

var result = type.init // error

Implicit Member Expression

In previous examples we used explicit .type-member expressions. When the type can be inferred, you can use an abbreviated form for enumeration cases or class methods. Inside the classes you don’t need the dot syntax to access methods, initializers, and so forth. The only time you have to be explicit is when the name of an argument to a method is the same as the property name.

var domainMask : NSSearchPathDomainMask = .UserDomainMask

With explicit member expression, in contrast, you explicitly access the value:

var instance = SomeClass()


For tuples, the member items are accessed by numeric dereference:

var myTuple = (a, b, c, d)

myTuple.1 // returns b


One of the features of Swift is the optional type. When you declare an optional variable, you are telling the compiler that this variable might or might not have a value. To get a valid value from an optional is called unwrapping the optional.

If you know that the value of an optional is not nil, you can forceably unwrap using the ! (bang) operator. If the value that’s unwrapped is not a valid value, you will get a runtime error.

var a : Int? = 0

var b : Int = 5

a! += b

The result of an optional expression is always an optional type


This expression returns the value as an optional. The way it works is that if the optional unwraps as a valid value, the rest of the expression is evaluated and the result is returned, otherwise nil is returned.

class SomeClass {

        func someFunction() -> Int {

                 return 42



var someInstance : Int?

var result = someInstance?.someFunction()

The type of the result is Int? because even though the return type of someFunction is Int, someInstance is an optional. If someInstance exists, the result will have the value 42; if someInstance is nil then result will be nil.

There is another way to optionally unwrap an optional using the if-let expression.

if let unwrapped = someInstance {

        result = unwrapped.someFunction()


In this case, if someInstance has a valid value, it is assigned to unwrapped and then the if statement is evaluated to be true and the statements in the if statement are executed, otherwise the condition for the if statement is evaluated to be false and it’s skipped.

Optional Chainning

Optional chainning is another operator ?? (two questions together) where you give a list of the exrepssions that return optional value of the same type, then first expression that returns a valid valid it is used. The simplist form is two expressions separated by ??

exrepssion1 ?? expression2

if the expression1 has a valid value then expression2 is ignored and value return from expression1 is used. You can chain multiple of these together

expression1 ?? expression2 ?? expression3 ?? "Valid String"

In the above example all expression must return a string type, if none of them return a valid string value then the "Valid String" is returned.


This was a quick overview of expressions; there’s a lot more to learn and experiment with. You’ll be using most if not all of these expressions in your programs. You learned about optionals, and optional chaining how it can help you write safer code.

Copyright information

© Waqar Malik 2015

Authors and Affiliations

  • Waqar Malik
    • 1
  1. 1.CAUS

Personalised recommendations