0% found this document useful (0 votes)
9 views89 pages

(M2-MAIN) Swift Syntax

This document provides an overview of Swift syntax, covering constants, variables, data types, control structures, and collections such as arrays, sets, and dictionaries. It emphasizes the importance of type safety, optional values, and various operators in Swift programming. Additionally, it explains how to manipulate strings and use control flow constructs to manage program execution.

Uploaded by

Charles Uy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views89 pages

(M2-MAIN) Swift Syntax

This document provides an overview of Swift syntax, covering constants, variables, data types, control structures, and collections such as arrays, sets, and dictionaries. It emphasizes the importance of type safety, optional values, and various operators in Swift programming. Additionally, it explains how to manipulate strings and use control flow constructs to manage program execution.

Uploaded by

Charles Uy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

Mobile Application

Development 2
IT0093
Module 2
Swift Syntax
• To familiarize with swift basic syntax
• To use implicitly and explicitly define a data type
• To understand the advance control structure of swift
• To manipulate string
• To define an optional and optional binding
• To use tuples and collection in creating an application
Introduction to Swift
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
Constants uses the let keyword
Variables uses the var keyword
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.

The colon in the declaration means “…of type…,”


Constant and variable names can contain almost any
character, including Unicode characters:

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.
You can print the current value of a constant or variable with the
print(_:separator:terminator:) function:

Swift uses string interpolation to include the name of a constant or


variable as a placeholder in a longer string, and to prompt Swift to
replace it with the current value of that constant or variable. Wrap the
name in parentheses and escape it with a backslash before the
opening parenthesis:
Use comments to include non-executable text in your code, as a note
or reminder to yourself. Comments are ignored by the Swift compiler
when your code is compiled.
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.

Int
• On a 32-bit platform, Int is the same size as Int32.
• On a 64-bit platform, Int is the same size as Int64.
Uint
• On a 32-bit platform, UInt is the same size as UInt32.
• On a 64-bit platform, UInt is the same size as UInt64.
Floating-point numbers are numbers with a fractional component, such
as 3.14159, 0.1, and -273.15.

• Double represents a 64-bit floating-point number.


• Float represents a 32-bit floating-point number.
Swift is a type-safe language. A type safe language
encourages you to be clear about the types of values
your code can work with. If part of your code expects
a String, you can’t pass it an Int by mistake.
Type inference enables a compiler to deduce the type of a particular
expression automatically when it compiles your code, simply by
examining the values you provide.
Integer literals can be written as:
• A decimal number, with no prefix
• A binary number, with a 0b prefix
• An octal number, with a 0o prefix
• A hexadecimal number, with a 0x prefix
For decimal numbers with an exponent of exp, the base number is
multiplied by 10exp:
• 1.25e2 means 1.25 x 102, or 125.0.
• 1.25e-2 means 1.25 x 10-2, or 0.0125.
For hexadecimal numbers with an exponent of exp, the
base number is multiplied by 2exp:
• 0xFp2 means 15 x 22, or 60.0.
• 0xFp-2 means 15 x 2-2, or 3.75.
Type aliases define an alternative name for an
existing type. You define type aliases with the
typealias keyword.
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.
You use optionals in situations where a value may be absent. An
optional says:
There is a value, and it equals x or There isn’t a value at all
The exclamation mark 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:
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.
Implicitly unwrapped optionals are useful when an optional’s value is
confirmed to exist immediately after the optional is first defined and
can definitely be assumed to exist at every point thereafter. The
primary use of implicitly unwrapped optionals in Swift is during class
initialization.
• 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 assignment operator (a = b) initializes or updates the
value of a with the value of b:
Swift supports the four standard arithmetic operators for
all number types:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
• If the operator is written before the variable, it
increments the variable before returning its value.
• If the operator is written after the variable, it
increments the variable after returning its value.
• 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)
• The ternary conditional operator is a special operator with three
parts, which takes the form question ? answer1 : answer2. It is a
shortcut for evaluating one of two expressions based on whether
question is true or false. If question is true, it evaluates answer1 and
returns its value; otherwise, it evaluates answer2 and returns its
value.
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 is stored inside a.
• The closed range operator (a...b) defines a range that runs
from a to b, and includes the values a and b. The value of a
must not be greater than b.
• The half-open range operator (a..<b) defines a range that runs
from a to b, but does not include b.
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 NOT (!a)
Logical AND (a && b)
Logical OR (a || b)
A string is a series of characters, such as "hello, world" or
"albatross". Swift strings are represented by the String type.
The contents of a String can be accessed in various ways,
including as a collection of Character values.

String Literals
A string literal is a fixed sequence of textual characters
surrounded by a pair of double quotes ("").
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):
Swift’s String type is a value type. If you create a new String
value, that String value is copied when it is passed to a
function or method, or when it is assigned to a constant or
variable.

Swift’s 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.
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.
Inserting and Removing
Prefix and Suffix Equality
Control Structures
Swift provides all the familiar control flow constructs of C-
like languages. These include for and while loops to perform
a task multiple times; if 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.
• for-in performs a set of statements for each item in a
range, sequence, collection, or progression.
• for-condition-increment performs a set of statements until
a specific condition is met, typically by incrementing a
counter each time the loop ends.
General Syntax
• while evaluates its condition at the start of each pass through the
loop.
• do-while evaluates its condition at the end of each pass through the
loop.
if statement has a single if condition. It executes a set of
statements only if that condition is true.
The if statement can provide an alternative set of statements, known as an else
clause, for when the if condition is false. These statements are indicated by the
else keyword:
if condition{statements}
else {statements}
You can chain multiple if statements together, to consider additional clauses:
if condition {statements}
else if condition {statements}
else{statements}
In its simplest form, the if statement
has a single if condition. It executes
a set of statements only if that
condition is true:
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.
Control transfer statements change the order in which
your code is executed, by transferring control from one
piece of code to another. Swift has four control transfer
statements:
• continue
• break
• fallthrough
• return
The continue statement tells a
loop to stop what it is 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 break statement ends execution of an entire
control flow statement immediately. The break
statement can be used inside a switch statement or
loop statement when you want to terminate the
execution of the switch or loop statement earlier than
would otherwise be the case.
Switch statements in Swift do not fall through the bottom of each case
and into the next one. Instead, the entire switch statement completes
its execution as soon as the first matching case is completed.
You can nest loops and switch statements inside other loops and
switch statements in Swift to create complex control flow structures.
However, loops and switch statements can both use the break
statement to end their execution prematurely. Therefore, it is
sometimes useful to be explicit about which loop or switch 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.
Example labeled
syntax in a while
loop
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 is not true.
• Arrays are ordered collections of values.
• Sets are unordered collections of unique values.
• Dictionaries are unordered collections of key-value
associations.
Arrays, sets, and dictionaries in Swift are always clear about the types
of values and keys that they can store. This means that you cannot
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.

If you create an array, a set, or a dictionary, and assign it to a variable,


the collection that is created will bemutable. This means that you can
change (or mutate) the collection after it is created by adding,
removing, or changing items in the collection. If you assign an array, a
set, or a dictionary to a constant, that collection isimmutable, and its
size and contents cannot be changed.
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.

Empty Array
Array with a Default Value

Adding Two Arrays Together


Array Literals

Or

inferred
A set stores distinct values of the same type in a collection with no
defined ordering. You can use a set instead of an array when the order
of items is not important, or when you need to ensure that an item only
appears once.

Creating and Initializing an Empty Set


Set with an Array Literal

Inferred
• Use the intersect(_:) method to create a new set with only the values common to
both sets.
• Use the exclusiveOr(_:) method to create a new set with values in either set, but
not both.
• Use the union(_:) method to create a new set with all of the values in both sets.
• Use the subtract(_:) method to create a new set with values not in the specified
set.
• Use the “is equal” operator (==) to determine whether two sets contain all of the same
values.
• Use the isSubsetOf(_:) method to determine whether all of the values of a set are contained
in the specified set.
• Use the isSupersetOf(_:) method to determine whether a set contains all of the values in a
specified set.
• Use the isStrictSubsetOf(_:) or isStrictSupersetOf(_:) methods to determine whether a set is
a subset or superset, but not equal to, a specified set.
• Use the isDisjointWith(_:) method to determine whether two sets have any values in
common.
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.

Empty Dictionary

Dictionary Literals

inferred

You might also like