You are on page 1of 38

The Complete Guide For

Programming Language

Part 2 By: Hossam Ghareeb


hossam.ghareb@gmail.com
Contents
● Classes ● Type Casting
● Inheritance ● Any Vs AnyObject
● Computed Properties ● Protocols
● Type Level ● Delegation
● Lazy ● Extensions
● Property Observers ● Generics
● Structures ● Operator Functions
● Equality Vs Identity
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.
Classes
● Student class example
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.
Classes
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.
Inheritance
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.
Computed Properties
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.
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.
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 =>
Property Observers
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
Structures
Check example:
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
Equality Vs Identity
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:
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
Type Casting
In this example you will see how to use as?
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:
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:
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.
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.
Protocols example:
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.
Protocols Composition
● If you want a type to conform to multiple protocols use the form
protocol<SomeProtocol, AnotherProtocol>
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:
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
Extension Examples
Define new initializers:
We will add a new initializer for CGRect , to accept center point, width
and height.
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.
Extension Examples
Define mutating methods:
Add methods that modify in the instance itself (mutate it):
Extension Examples
Protocol adoption with Extension:
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:
Generics
We will build a stack
data structure with
generic type. It can be
stack of Strings, Ints,
….. or even custom
objects.
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


Operators Functions

You might also like