Download presentation
Presentation is loading. Please wait.
Published byAlexis Clark Modified over 6 years ago
1
The Complete Guide For Programming Language Part 1
The Complete Guide For Programming Language Part 1 By: Hossam Ghareeb
2
Contents. Closures (Blocks) About Swift Arrays
Dictionaries Enum 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
3
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.
4
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:
5
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.
6
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:
7
Variables & Constants.
8
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:
9
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:
10
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:
11
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.
12
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.
13
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.
14
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:
15
If With Optionals
16
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:
17
Switch
18
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
19
Switch Cont.
20
Switch With Ranges. In Swift you can use the range of values for checking in case statements. Ranges are identified with "..." in Swift :
21
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:
22
Switch With Tuples. Decomposing: Use underscore "_" to ignore parts:
23
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:
24
Switch With Tuples. Using tuples with functions:
25
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:
26
Switch With Tuples.
27
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:
28
Switch With "Where" "Where" is used with case statement to add additional condition. Check these examples:
29
Switch With "Where" Another example in using "Where":
30
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
31
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:
32
Functions Using names for local variables
33
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:
34
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:
35
Functions Using default parameter value:
Functions can take variable number of arguments using '...' :
36
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:
37
Passing & Returning Functions
38
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.
39
Closures Example #1, using map with an array. map returns an array with result of each item
40
Closures Example #2 of using closure as completion handler when sending api request
41
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
42
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.
43
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 "+=" :
44
Arrays You can retrieve and update array using subscript syntax. You will get runtime error if you tried to access item out of bound.
45
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.
46
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 :)
47
Dictionaries
48
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'
49
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.
50
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")
51
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.
52
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.
53
Enum With Raw Values Example:
54
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.
55
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 ME
56
The Complete Guide For Programming Language Part 2
The Complete Guide For Programming Language Part 2 By: Hossam Ghareeb
57
Contents Classes Inheritance Computed Properties Type Level Lazy
Property Observers Structures Equality Vs Identity Type Casting Any Vs AnyObject Protocols Delegation Extensions Generics Operator Functions
58
Classes Swift is Object oriented language and you can create your own custom classes . In Swift, you don't have to write interface and implementation files like Obj-C. Just one file and Swift will care about everything. You can create classes with the keyword "class" and then you can list all your attributes and methods. In creating new instances of your class, you don't need for keywords like new, alloc, init . Just the class name and empty parentheses (). Class instances are passed by reference.
59
Classes Student class example
60
Classes As in previous example, you can list easily your attributes. In Swift class, attributes should have one of 3 conditions : Defined with initial value like firstName. Defined with Optional value like middleName. Initialized inside the default initializer lastName. init() function is used to make a default initializer for the class. You can create multiple initializers that accept parameters. Methods are created easily like functions syntax. Deinitializer using deinit() can be use to free up any resources that this instance holds them.
61
Classes
62
Inheritance In Swift, a class can inherit from another class using ":"
Unlike Objective-C, a Swift class doesn't inherit from base class or anything by default. Calling super is required when overriding any initializer from super class. Use the keyword override when you want to override a function from your super class. Use the keyword final before a class name to prevent it from being inherited. Also you can use it before a function name to prevent it from being overridden.
63
Inheritance
64
Computed Properties All previous properties are called "stored properties", because we store values on them. In Swift, we have other type called "Computed properties" as these properties don't store anything but they compute the value from other properties. Open curly braces { } after property to write the code of computing. You can do this if you wanna getter only. If you want to override setter , you will type code inside set{ } and getter inside get { } If you didn't provide setter set { } the property will be considered as readOnly A value called newValue will be available in setter to be used.
65
Computed Properties
66
Type Level TypeLevel in Swift is a way to define properties and methods called by Type itself, not by instance (like class methods) Write the keyword class before attribute or function to make it as type level.
67
Lazy Lazy keyword is used before var attributes (var only not let) to
mark it as lazy initialized. It means that, initialize it only when it will be used. So when you try to access this attribute it will be initialized to be used, otherwise it will remain nil.
68
Property Observers Suppose you want to keep track about every change in a property in a class. Swift gives you an awesome way to track it before and after change using willSet { } and didSet { } In next example, we wanna keep track on player score. Also we have a limit 1000 points in score, so if the score is set to value more than 1000, it will remain 1000. newValue is given in willSet { } and oldValue is given in didSet { } If you want to change the names of newValue and oldValue do the following =>
69
Property Observers
70
Structures Structures and classes are very similar in Swift. Structures can define properties, methods, define initializers, computed properties and conform to protocols. Structures don't have Inheritance, Type Casting or Deinitializers String, Array and Dictionary are implemented as Structures! Structures are value types, so they are passed by value . When you assigned it to another value, the struct value is copied. Structures have an automatically memberwise initializers to initialize your properties
71
Structures Check example:
72
Equality Vs Identity We always used to use "==" for checking in equality. In Swift there is another thing called Identity "===" and "!==". Its used only with Objects to check if they point to the same object. Identity is used only with objects. You cannot use it with structures. Two objects can be equal but not identical. Because they may have the same values but they are different objects
73
Equality Vs Identity
74
Type Casting TypeCasting is a way for type checking and downcasting objects. check this: we created array of controls. As we know that Array should be typed, Swift compiler found that they are different in type, so it had to look for their common superclass which is UIView so this array is of type UIView. We will use is keyword to check the type of object, check example:
75
Type Casting If I wanted to use component, you can't because its UIView type. To use it we can cast it to UILabel using as keyword. Use as if you really sure that the downcast will work because it will give runtime error if not. Use as? if you are not sure, it will return nil if downcast fails
76
Type Casting In this example you will see how to use as?
77
Any Vs AnyObject In Swift you can set the type of object to AnyObject, its equivalent to id in Objective-C. You can use it with arrays or dictionaries or anything. AnyObject holds only Objects (class type references). Any can be anything like objects, tuples, closures,..... Use is, as and as? to downcast and check the type of Any or AnyObject Check examples:
78
Any Vs AnyObject objects array has String, Label and Date !! so the compiler will try to get their common super class of them, it will ended by "AnyObject". But someone can say, "55 & true are not objects ???". In fact, they are because in runtime Swift bridged them to Foundation classes. So String will be bridged to NSString, Int & Bools will be bridged to NSNumber. The common superclass for them now will be NSObject which is equivalent to AnyObject in Swift AnyObject is like id, you can send any message to them (call any function), but in runtime will give error is doesn't respond to this message. check example:
79
Any Vs AnyObject Here in runtime we got this error, because obj became of type Number which doesn't respond to this method. So to avoid this you have to use is as or as? to help check the type before using the object.
80
Protocols Protocols can easily be created using keyword protocol.
Methods and properties can be listed between { } to be implemented by class which conforms to this protocol Protocol properties can be readonly by adding {get} OR settable and gettable by adding {get set} . Classes can conform to multiple protocols. Structures and enumerations can conform to protocols. You can use protocols as types in variables, properties, function return type and so on. Protocols can inherit one or more protocols.
81
Protocols example:
82
Protocols Add the keyword class in
inheritance list after ':' to limit protocol adoption to classes only (No structures or enumerations) When using protocols with structures and enumerations, add the keyword mutating before func to indicate that this method is allowed to modify the instance it belongs or any properties in it.
83
Protocols Composition
If you want a type to conform to multiple protocols use the form protocol<SomeProtocol, AnotherProtocol>
84
Checking For Protocol Conformance
Use is, as or as? to check for protocol conformance. You must mark your protocol attribute to check for protocol conformance. @objc protocols can be adopted only by classes. @objc attribute tells compiler that this protocol should be exposed to Objective-C code.
85
Optional Requirements In Protocols
Attributes and methods can be optional by prefixing them with the keyword optional. It means that they don't have to be implemented. You check for an implementation of an optional requirement by writing ? after the requirement. Thats because the optional property or method that return value will return Optional value so you can check it easily Optional protocol requirements can only be specified if your protocol is marked with attribute
86
Delegation Delegation is the a best friend for any iOS developer and I think there is no developer didn't use it before. Defining delegate property as optional is useful for not required delegates OR to use its initial value nil, so when you use it as nil you will not get errors ( Remember you can send msgs to nil) Check example:
87
Delegation Delegation example
88
Extensions Extensions are like Categories in Objective-C
You can use it with classes, structures and enumerations. They are not names like categories in Objective-C You can add properties, instance and class methods, new initializers, nested types, subscripts and make it conform to a protocol. Extensions can be created by this form:
89
Extension Examples Using computed properties:
Here we have Double value to represent meters, we need it in Km and Cm, we add an extension for Double
90
Extension Examples Define new initializers:
We will add a new initializer for CGRect , to accept center point, width and height.
91
Extension Examples Define new methods:
In this example we will add new method in Int, it will take a closure to run it with int value times.
92
Extension Examples Define mutating methods:
Add methods that modify in the instance itself (mutate it):
93
Extension Examples Protocol adoption with Extension:
94
Generics Generics is used to write reusable functions that can apply for any type. Example for generics: Arrays and Dictionaries. You can create Array with any type and once declared, it works with this kind. Suppose you need a function that takes array as parameter and returns the first and last elements. In Swift you have to tell the function the type of array and type of return values. So this will not work for any kind of array. If you used AnyObject, the returned values will be of kind AnyObject and you have to cast them! To solve this we will use generics, check exmaple:
95
Generics We will build a stack data structure with generic type. It can be stack of Strings, Ints, ….. or even custom objects.
96
Operator Functions Classes and structures can provide their own implementation of operators (Operator overloading). You can add your custom operators and override them. Check example, we will add some operators functions for CGVector
97
Operators Functions
98
Thanks! If you liked the tutorial, please share and tweet with your friends. If you have any comments or questions, don't hesitate to ME
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.