55
By: Hossam Ghareeb [email protected] Part 1 The Complete Guide For Programming Language

Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Embed Size (px)

DESCRIPTION

Complete Guid for the new programming language 'Swift' for developing apps for iOS and OS X. Swift is an alternative for Objective-C language.

Citation preview

Page 1: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

By: Hossam [email protected]

Part 1

The Complete Guide For

Programming Language

Page 2: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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

Page 3: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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.

Page 4: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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:

Page 5: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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.

Page 6: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Variables & Constants.

In Swift, use 'let' for constans and 'var' for variables. In constants you can't change the value of a constant after being initialized and you must set a value to it.

Although you use 'var' or 'let' for variables, Swift is typed language. The type is written after ':' . You don't have to write the type of variable or constant because the compiler will infer it using its initial value.

BUT if you didn't set an initial value or the initial value that you provided is not enough to determine the type, you have to explicitly type the variable or constants.

Check examples:

Page 7: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Variables & Constants.

Page 8: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Variables & Constants.

In Objective-C we used to use mutability, for example:

NSArray and NSMutableArray or NSString and NSMutableString

In Swift, when you use var, all objects will be mutable BUT when you use let, all objects will be immutable:

Page 9: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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:

Page 10: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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:

Page 11: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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.

Page 12: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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.

Page 13: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

If

● Conditions must be Boolean, true or false. Thus, the next code will not work as it was working in Objective-C :

As you see in Swift, you cannot check in variable directly like Objective-C.

Page 14: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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:

Page 15: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

If With Optionals

Page 16: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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:

Page 17: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch

Page 18: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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:

● As you see, each case must contain at least one executable statement.

● Multiple matches for single case can be separated by commas and no need for fallthrough cases

Page 19: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch Cont.

Page 20: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch With Ranges.● In Swift you can use the range of values for checking in case

statements. Ranges are identified with "..." in Swift :

Page 21: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch With Tuples.Tuples are used to group multiple values in a single compound value. Each value can be in any type. Values can be with any number as you like:

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:

Page 22: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch With Tuples.● Decomposing:

● Use underscore "_" to ignore parts:

Page 23: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch With Tuples.● You can use element index to access tuple values. Also you can

name the elements and access them by name:

● With dictionary:

Page 24: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch With Tuples.Using tuples with functions:

Page 25: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch With Tuples.

Now we will see tuples with switch. We will use it in checking that a point is located inside a box in grid. Also we want to check if the point located on x-axis or y-axis. Here is the gird:

Page 26: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch With Tuples.

Page 27: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch With Value Binding

You can bind the values of variables in switch case statements to temporary constants to be used inside the case body:

Page 28: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch With "Where"

"Where" is used with case statement to add additional condition. Check these examples:

Page 29: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Switch With "Where"

Another example in using "Where":

Page 30: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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

Page 31: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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 ':'

● You can describe or name the local variables of function like Objective-C by writing the name before the local variable OR add '#' if the local variable is already an appropriate name. Check examples:

Page 32: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Functions● Using names for local variables

Page 33: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Functions● In Swift, params are considered as constants and you can't change

them.

● To change local variables, copy the values to other variables OR tell Swift that this value is not constant by writing 'var' before the name:

Page 34: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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:

Page 35: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Functions● Using default parameter value:

● Functions can take variable number of arguments using '...' :

Page 36: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Passing & Returning Functions● In Swift, functions are first class objects. Thus they can be passed

around● Every function has type like this:

● You can pass a function as parameter or return it as a result. Check examples:

Page 37: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Passing & Returning Functions

Page 38: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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.

Page 39: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Closures● Example #1, using map with an array. map returns an array with

result of each item

Page 40: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Closures● Example #2 of using closure as completion handler when sending

api request

Page 41: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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

Page 42: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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.

Page 43: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Arrays● Creating and initializing array is easy. Also you can create array

with certain size and default value for items:

● For appending items, use 'append' method or "+=" :

Page 44: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Arrays● You can retrieve and update array using subscript syntax. You will

get runtime error if you tried to access item out of bound.

Page 45: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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.

Page 46: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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 :)

Page 47: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Dictionaries

Page 48: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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'

Page 49: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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.

Page 50: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Enum With Associated Values● Enum values can be used with associated values. Lets explain with

an example. Suppose you describe products in your project, each product has a barcode. Barcodes have 2 types (UPC, QRCode)

● UPC code can be represented by 4 Integers (4,88581,01497,3), and QR code can be represented by String ("ABCFFDF")

Page 51: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Enum With Associated Values● So we need to represent the barcode with two condition UPC and

QR , each one has associated values to give full information.

Page 52: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Enum With Raw Values● For sure in some cases you need to define some constants in

enum with their values. For example the power of monster has different values based on game level (easy = 50, medium = 60, hard = 80, very hard = 120) and these values are constant. So you need to make enum for power values and in same time save these values. You can create enum with cases values but they must be in same type and this type is written after enum name. Also you can use .rawValue to get the constant value.

● You can initialize an enum value using its constant value using this format EnumName(rawValue: value). It returns the enum that map to the given value. Be careful because the value returned is Optional, it may contain an enum or nil, BECAUSE Swift can guarantee that the given constant is exist in enum or not.

Page 53: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Enum With Raw Values Example:

Page 54: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

Enum With Raw Values Example:● Raw values can be Strings, Chars, Integers or floating point

numbers. In using Integers as a type for raw values, if you set a value of any case, others auto_increment if you didn't specify values for them.

Page 55: Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

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.

If you have any comments or questions, don't hesitate to email ME