Professional Documents
Culture Documents
Programming Language
Part 1
Contents.
About Swift
Hello World! with playground
Variables & Constants
Printing Output
Type Conversion
If
If with optionals
Switch
Switch With Ranges.
Switch With Tuples.
Switch With Value Binding
Switch With "Where"
Loops
Functions
Passing & Returning Functions
Closures (Blocks)
Arrays
Dictionaries
Enum
About Swift
Swift is a new scripting programming language for iOS and OS X
apps.
Swift is easy, flexible and funny.
Unlike Objective-C, Swift is not C Compatible. Objective-C is a
superset of C but Swift is not.
Swift is readable like Objective-C and designed to be familiar to
Objective-C developers.
You don't have to write semicolons, but you must write it if you
want to write multiple statements in single line.
You can start writing apps with Swift language starting from
Xcode 6.
Swift doesn't require main function to start with.
Hello World!
As usual we will start with printing "Hello World" message. We will
use something called playground to explore Swift language. It's an
amazing tool to write and debug code without compile or run.
Create or open an Xcode project
and create new playground:
Hello World!
Use "NSLog" or "println" to print message to console. As you see in
the right side you can see in real time the values of variables or
console message.
Printing Output
We introduced the new way to print output using println(). Its
very similar to NSLog() but NSLog is slower, adds timestamp to
output message and appear in device log. Println() appear in
debugger log only.
In Swift you can insert values of variables inside String using "\()" a
backslash with parentheses, check example:
Type Conversion
Swift is unlike other languages, it will not implicitly convert types of
result of statements. Lets check example in Obj-C :
In Swift you can't do this. You have to decide the type of result by
explicitly converting it to Double or Integer. Check next example:
Type Conversion
Here we should convert any one of them so the two variables be in same
type.
Swift guarantees safety in your code and makes you decide the type of
your result.
If
In Swift, you don't have to add parentheses around the condition.
But you should use them in complex conditions.
Curly braces { } are required around block of code after If or else.
This also provide safety to your code.
If
Conditions must be Boolean, true or false. Thus, the next code
will not work as it was working in Objective-C :
If With Optionals
You can set the variable value as Optional to indicate that it may
contain a value or nil.
Write question mark "?" after the type of variable to mark it as
Optional.
Think of it like the "weak" property, it may point to an object or nil
Use let with If to check the Optional value. If the optional value is
nil, the conditional will be false. OtherWise, the it will be true and
the value will be assigned to the constant of let
Check example:
If With Optionals
Switch
Switch works in Swift like many other languages but with some new
features and small differences:
It supports any kind of data, not only Integers. It checks for
equality.
Switch statement must be exhaustive. It means that you have to
cover (add cases for) all possible values for your variable. If you
can't provide case statement for each value, add a default
statement to catch other values.
When a case is matched in switch, the program exits from the
switch case and doesn't continue checking next cases. Thus, you
don't have to explicitly break out the switch at the end of each
case.
Check examples:
Switch
Switch Cont.
As we said, there is no fallthrough in switch statements and
therefore break is not required. So code like this will not work in
Swift:
Switch Cont.
You can decompose the values of tuples with many ways as you will
see in examples. Most of time, tuples are used to return multiple
values from function. Also can be use to enumerate dictionary
contents as (key, value). Check examples:
With dictionary:
Loops
Like other languages, you can use for and for-in loops without
changes. But in Swift you don't have to write the parentheses.
for-in loops can iterate any collection of data. Also It can be used
with ranges
Functions
Functions are created using the keyword 'func'.
Parentheses are required for functions that don't take params.
In parameters you type the name and type of variable between ':'
Functions
Using names for local variables
Functions
In Swift, params are considered as constants and you can't change
them.
Functions
To return values, you have to write the type of returned info after
'()' and "->". Use tuples to return multiple values at once.
In Swift, you can use default parameter values. BUT be aware that
when you wanna use function with default-valued params, you
must write the name of the argument when you wanna use it.
Check examples:
Functions
Using default parameter value:
Closures
Closures are very similar to blocks in C and Objective-C.
Closures are first class type so it can be nested , returned and
passed as parameter. (Same as blocks in Objective-C)
Functions are special cases of closures.
Closures are enclosed in curly braces { } , then write the function
type (arguments) -> (return type), followed by in keyword that
separate the closure header from the body.
Closures
Example #1, using map with an array. map returns an array with
result of each item
Closures
Example #2 of using closure as completion handler when sending
api request
Closures
Example #3, using the built-in "sorted" function to sort any
collection based on a closure that will decide the compare result
of any two items
Arrays
Arrays in Swift are typed. You have to choose the type of array,
array of Integers, array of Strings,....etc. That's different from
Objective-C where you can create array with items of any type.
You can write the type of array between square brackets [ ] OR If
you initialized it with data, Swift will infer the type of array
implicitly.
Arrays by default are mutable arrays, except if you defined it as
constant using 'let' it will be immutable.
Length of array can be know by .count property, and you can
check if is it empty or not by .isEmpty property.
Arrays
Creating and initializing array is easy. Also you can create array
with certain size and default value for items:
Arrays
You can retrieve and update array using subscript syntax. You will
get runtime error if you tried to access item out of bound.
Arrays
You can easily iterate over an array using 'for-in' , 'for' or by
'enumerate'. 'enumerate' gives you the item and its index during
enumeration.
Dictionaries
Dictionary in Swift is similar to one in Objective-C but like Array,
Dictionary is strongly typed, all keys must be in same type and all
values must be in same type.
Type of Dictionary is inferred by initial values or you have to write
the type between square brackets [ KeyType, ValueType]
Like Arrays, Dictionaries by default are mutable dictionaries,
except if you defined it as constant using 'let' it will be immutable.
Check examples :)
Dictionaries
Enum
Enum is very popular concept if you have specific values of
something.
Enum is created by the keyword 'enum' and listing all possible
cases after the keyword 'case'
Enum
Enum can be used easily in switch case but as we know that switch
in Swift is exhaustive, you have to list all possible cases.
Thanks
We have finished Part 1.
In next parts we will talk about Classes, Structures, OOP and some
advanced features of Swift.
If you liked the tutorial, please share and tweet with your friends.