Swift Tutorial
Swift Introduction
Swift Playground
“On a Mac with Xcode installed, or on an iPad with Swift Playgrounds, you can open this chapter as a playground. Playgrounds allow you to edit the code listings and see the result immediately.”
After download the sample playground file, click on the run
button on the left and bottom screen. Then you can see the running result on the right screen. Playground is a kind of file like Jupyter notebook or R Markdown.
Hello Swift
You can show result on the next line of the code. And edit the code you like.
Docstring
Use //
for one line comment.
Use /**
and */
for multi-line comments.
1 | // This is one line comment. |
1 | /** |
let & var
Use let
to make a constant and var
to make a variable. The value of a constant doesn’t 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.
1 | var myVariable = 42 |
You cannot modify a constant.
1 | myConstant = 50 |
A constant or variable must have the same type as the value you want to assign to it. However, you don’t 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 doesn’t provide enough information (or if isn’t an initial value), specify the type by writing it after the variable, separated by a colon.
1 | let implicitInteger = 70 |
Convert Data Type through constructor
Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type. Like type constructor in Python.
1 | let label = "The width is " // constant string |
1 | let widthLabel = label + width |
Convert Data Type through \
There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash (\
) before the parentheses. For example:
1 | let apples = 3 |
You cannot multiply int
and Float
1 | let applePrice = 0.99 |
Use \()
to include a floating-point calculation in a string and to include someone’s name in a greeting.
1 | let applesTotalPrice = "Total apple prices is \(Double(apples) * applePrice)" |
Multiple Lines
Use three double quotation marks ("""
) for strings that take up multiple lines. Indentation at the start of each quoted line is removed, as long as it matches the indentation of the closing quotation marks. For example:
1 | let quotation = """ |
array & dictionaries
Create arrays and dictionaries using brackets ([]
), and access their elements by writing the index or key in brackets. A comma is allowed after the last element.
array
Create an array.
1 | var shoppingList = ["catfish", "water", "tulips"] |
Replace element in array.
1 | shoppingList[1] = "bottle of water" |
Arrays automatically grow as you add elements.
1 | shoppingList.append("blue paint") |
dictionary
Create a dictionary
1 | var occupations = [ |
Add element in dictionary
1 | // ["Kaylee": "Mechanic", "Malcolm": "Captain"] |
Empty array or dictionary
To create an empty array or dictionary, use the initializer syntax.
1 | let emptyArray = [String]() |
Infer array or dictionary
If type information can be inferred, you can write an empty array as []
and an empty dictionary as [:]
—for example, when you set a new value for a variable or pass an argument to a function.
1 | shoppingList = [] |
Swift Data Type
Swift Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
1 | def myFunc(): |
1 | func myFunc() { |
Calling a Function
To call a function, use the function name followed by parenthesis:
1 | def myFunc(): |
1 | func myFunc() { |
Arguments
Information(Parameters) can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (name
). When the function is called, we pass along a first name, which is used inside the function to print the full name:
1 | # A function prints hello name. |
1 |
|
Arguments are often shortened to args in Python documentations.
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed into a function.
From a function’s perspective:
- A parameter is the variable listed inside the parentheses in the function definition.
- An argument is the value that are sent to the function when it is called.
Required Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
1 | # A function prints capitalized name |
Arguments are often shortened to args in Python documentations.
args are positional arguments.
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function, add a *
before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
1 | # A function prints capitalized name |
Arbitrary Arguments are often shortened to *args in Python documentations.
*args are positional arguments.
Keyword Arguments, kwargs
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
1 | # A function prints capitalized name with a title |
The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
kwargs are NOT positional arguments.
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into your function, add two asterix: **
before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items accordingly:
1 | # A function prints capitalized name with a title |
Arbitrary Keyword Arguments are often shortened to *kwargs* in Python documentations.
*kwargs* are NOT positional arguments
Default Parameter Value
If we call the function without argument, it uses the default value:
1 | # A function prints capitalized name with a title and country |
Keyword-only Arguments
If we use keyword arguments, we cannot restrain what the user input.
Take the example from Default Parameter Value:
This function accept the unexpected parameter (gender).
1 | # A function prints capitalized name with a title and country |
We successfully import gener = "man"
to the function even it will not be executed. But it is still dangerous.
A keyword-only argument could help us restraining user input.
We can use *
to split the arguments. The arguments after *
are keyword-only arguments, which could have a default value.
This function prevents from the unexpected parameter (gender).
1 | # A function prints capitalized name with a title and country |
You can Also use *args to split the arguments:
1 | # A function prints capitalized name with a title and country |
Order of Arguments
Warning!!!
Basically, you must define a function in the following way to avoid SyntaxError: positional argument follows keyword argumen
:
1 | def function_name(positional arguments, keyword arguments): |
And the detailed order is:
- Positional arguments, arg
- Default arguments
- Arbitrary Arguments, *arg
- Keyword-only arguments
- Keyword arguments, kwargs
1 | # Notice in this example, country = "United States" is NOT a default argument; it is a Keyword-only arguments since it follows the *arg. |
Return Values
To let a function return a value, use the return
statement:
1 | # A function returns your bmi |
Return is one of the most important concepts! A deep learning could help us understand it
Here is a for
statement to print a series numbers in a range:
1 | for i in range(3): |
Let’s do the same thing in a function, then call it:
1 | # A function prints the values in a range one by one. |
You may understand that sometimes print()
and return()
all print the result on your screen:
1 | # A function RETURNS your bmi |
1 | # A function PRINTS your bmi |
However, if try to do the same thing in return
.
1 | # A function PRINTS the values in a range one by one. |
1 | # A function try to RETURN the values in a range one by one, but it doesn't work. |
This is weird, right? Why the function only print 0
on the screen? Because return
only runs once in a function! And everything after return
will be ignored!
1 | def hello_1(): |
From the official definition:return
may only occur syntactically nested in a function definition, not within a nested class definition.
If an expression list is present, it is evaluated, else None
is substituted.
return
leaves the current function call with the expression list (or None
) as return value.
When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.
The pass Statement
function
definitions cannot be empty, but if you for some reason have a function
definition with no content, put in the pass
statement to avoid getting an error.
1 | def my_function(): |
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.
1 | # A function returns exponentiation |
A program to calculate Fibonacci numbers
In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
$${\displaystyle F_{0}=0,\quad F_{1}=1,}$$
and
$${\displaystyle F_{n}=F_{n-1}+F_{n-2},}$$
for $n > 1$.
The beginning of the sequence is thus:
$${\displaystyle 0,;1,;1,;2,;3,;5,;8,;13,;21,;34,;55,;89,;144,;\ldots }{\displaystyle 0,;1,;1,;2,;3,;5,;8,;13,;21,;34,;55,;89,;144,;\ldots }$$
1 | # A function returns Fibonacci number |
A program for Exponential operation
In Python, you can execute Exponential operation in a easy way:
1 | def exp(x, n): |
Swift Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators
Swift Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations.
Operator | Name |
---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
% |
Modulus |
** |
Exponentiation |
// |
Floor division |
Swift Assignment Operators
Assignment operators are used to assign values to variables:
Operator | Example | Same As |
---|---|---|
= |
x = 5 | x = 5 |
+= |
x += 3 | x = x + 3 |
-= |
x -= 3 | x = x - 3 |
*= |
x *= 3 | x = x * 3 |
/= |
x /= 3 | x = x / 3 |
%= |
x %= 3 | x = x % 3 |
//= |
x //= 3 | x = x // 3 |
**= |
x **= 3 | x = x ** 3 |
&= |
x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= |
x ^= 3 | x = x ^ 3 |
>>= |
x >>= 3 | x = x >> 3 |
<<= |
x <<= 3 | x = x << 3 |
Swift Comparison Operators
Comparison operators are used to compare two values.
Operator | Name |
---|---|
== |
Equal |
!= |
Not equal |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
Swift Logical Operators
Logical operators are used to combine conditional statements.
Operator | Description | Example |
---|---|---|
&& |
Returns True if both statements are true | x < 5 && x < 10 |
|| |
Returns True if one of the statements is true | x < 5 or x < 4 |
! |
Reverse the result, returns False if the result is true | not(x < 5 and x < 10) |
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.
Operator | Description | Example |
---|---|---|
is |
Returns true if both variables are the same object | x is y |
is not |
Returns true if both variables are not the same object | x is not y |
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object.
Operator | Description | Example |
---|---|---|
in |
Returns True if a sequence with the specified value is present in the object | x in y |
not in |
Returns True if a sequence with the specified value is not present in the object | x not in y |
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers.
Operator | Name | Description |
---|---|---|
& |
AND | Sets each bit to 1 if both bits are 1 |
^ |
XOR | Sets each bit to 1 if only one of two bits is 1 |
~ |
NOT | Inverts all the bits |
<< |
Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off |
>> |
Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off |
| |
OR | Sets each bit to 1 if one of two bits is 1 |