SlideShare a Scribd company logo
By: Hossam Ghareeb 
hossam.ghareb@gmail.com 
Part 2 
The Complete Guide For 
Programming Language
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
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>
Checking For Protocol Conformance 
● Use is, as or as? to check for protocol conformance. 
● You must mark your protocol with @objc 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.
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 the @objc attribute
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:
Delegation 
Delegation 
example
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
Thanks! 
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

More Related Content

What's hot (20)

PDF
Swift Tutorial For Beginners | Swift Programming Tutorial | IOS App Developme...
Edureka!
 
PDF
Swift Introduction
Natasha Murashev
 
PPTX
difference between c c++ c#
Sireesh K
 
PPSX
Data types, Variables, Expressions & Arithmetic Operators in java
Javed Rashid
 
PPTX
Features of java 02
University of Potsdam
 
PPTX
Java tokens
shalinikarunakaran1
 
PDF
JavaScript for ABAP Programmers - 1/7 Introduction
Chris Whealy
 
PPTX
Introduction to C# Programming
Sherwin Banaag Sapin
 
PDF
A swift introduction to Swift
Giordano Scalzo
 
PPTX
Introduction to c++
somu rajesh
 
PPTX
Decision control structures
Rahul Bathri
 
PDF
Alice 4
Christian Medina
 
PPTX
principle of oop’s in cpp
gourav kottawar
 
PPT
The Kotlin Programming Language
intelliyole
 
PPTX
Dart presentation
Lucas Leal
 
PDF
JavaScript for ABAP Programmers - 2/7 Data Types
Chris Whealy
 
PPTX
Id and class selector
Jesus Obenita Jr.
 
PPTX
Advance C# Programming Part 1.pptx
percivalfernandez3
 
PDF
C# Dot net unit-2.pdf
Prof. Dr. K. Adisesha
 
Swift Tutorial For Beginners | Swift Programming Tutorial | IOS App Developme...
Edureka!
 
Swift Introduction
Natasha Murashev
 
difference between c c++ c#
Sireesh K
 
Data types, Variables, Expressions & Arithmetic Operators in java
Javed Rashid
 
Features of java 02
University of Potsdam
 
Java tokens
shalinikarunakaran1
 
JavaScript for ABAP Programmers - 1/7 Introduction
Chris Whealy
 
Introduction to C# Programming
Sherwin Banaag Sapin
 
A swift introduction to Swift
Giordano Scalzo
 
Introduction to c++
somu rajesh
 
Decision control structures
Rahul Bathri
 
principle of oop’s in cpp
gourav kottawar
 
The Kotlin Programming Language
intelliyole
 
Dart presentation
Lucas Leal
 
JavaScript for ABAP Programmers - 2/7 Data Types
Chris Whealy
 
Id and class selector
Jesus Obenita Jr.
 
Advance C# Programming Part 1.pptx
percivalfernandez3
 
C# Dot net unit-2.pdf
Prof. Dr. K. Adisesha
 

Viewers also liked (20)

PDF
Ieeepro techno solutions ieee dotnet project - privacy-preserving multi-keyw...
ASAITHAMBIRAJAA
 
PPT
Swift-Programming Part 1
Mindfire Solutions
 
PDF
iOS 10 & XCode 8, Swift 3.0 features and changes
Manjula Jonnalagadda
 
PDF
What's new in Swift 3
Marcio Klepacz
 
PDF
Swift 3 Programming for iOS : extension
Kwang Woo NAM
 
PPTX
Swift 3
Michael Shrove
 
PDF
Swift 3 Programming for iOS : Enumeration
Kwang Woo NAM
 
PDF
The Swift Programming Language with iOS App
Mindfire Solutions
 
PDF
iOSMumbai Meetup Keynote
Glimpse Analytics
 
PDF
Swift - the future of iOS app development
openak
 
PPTX
Medidata Customer Only Event - Global Symposium Highlights
Donna Locke
 
PDF
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Dennis Sweitzer
 
PDF
Medidata AMUG Meeting / Presentation 2013
Brock Heinz
 
PDF
Tools, Frameworks, & Swift for iOS
Teri Grossheim
 
PDF
Medidata Rave Coder
Nikolay Rusev
 
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
Jonathan Engelsma
 
PPTX
Beginning iOS Development with Swift
TurnToTech
 
PPTX
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
政斌 楊
 
PDF
Distributing information on iOS
Make School
 
PDF
Advanced Core Data
Make School
 
Ieeepro techno solutions ieee dotnet project - privacy-preserving multi-keyw...
ASAITHAMBIRAJAA
 
Swift-Programming Part 1
Mindfire Solutions
 
iOS 10 & XCode 8, Swift 3.0 features and changes
Manjula Jonnalagadda
 
What's new in Swift 3
Marcio Klepacz
 
Swift 3 Programming for iOS : extension
Kwang Woo NAM
 
Swift 3 Programming for iOS : Enumeration
Kwang Woo NAM
 
The Swift Programming Language with iOS App
Mindfire Solutions
 
iOSMumbai Meetup Keynote
Glimpse Analytics
 
Swift - the future of iOS app development
openak
 
Medidata Customer Only Event - Global Symposium Highlights
Donna Locke
 
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Dennis Sweitzer
 
Medidata AMUG Meeting / Presentation 2013
Brock Heinz
 
Tools, Frameworks, & Swift for iOS
Teri Grossheim
 
Medidata Rave Coder
Nikolay Rusev
 
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
Jonathan Engelsma
 
Beginning iOS Development with Swift
TurnToTech
 
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
政斌 楊
 
Distributing information on iOS
Make School
 
Advanced Core Data
Make School
 
Ad

Similar to Swift Tutorial Part 2. The complete guide for Swift programming language (20)

PDF
Swift, swiftly
Jack Nutting
 
PDF
From android/java to swift (3)
allanh0526
 
PDF
Quick swift tour
Kazunobu Tasaka
 
PDF
Objective-C to Swift - Swift Cloud Workshop 3
Randy Scovil
 
PDF
Introduction to Swift 2
Joris Timmerman
 
PDF
Swift, a quick overview
Julian Król
 
PDF
Custom view
SV.CO
 
PDF
Infinum iOS Talks #1 - Swift done right by Ivan Dikic
Infinum
 
PDF
Intro toswift1
Jordan Morgan
 
PDF
SV-ios-objc-to-swift
Randy Scovil
 
PDF
Protocol-Oriented Programming in Swift
Oleksandr Stepanov
 
PDF
Programming with Objective-C
Nagendra Ram
 
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
Jonathan Engelsma
 
PDF
Swift rocks! #1
Hackraft
 
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 02)
Jonathan Engelsma
 
PDF
Protocols promised-land-2
Michele Titolo
 
PDF
Developing Swift - Moving towards the future
Pablo Villar
 
PDF
Никита Корчагин - Programming Apple iOS with Objective-C
DataArt
 
PDF
How would you describe Swift in three words?
Colin Eberhardt
 
Swift, swiftly
Jack Nutting
 
From android/java to swift (3)
allanh0526
 
Quick swift tour
Kazunobu Tasaka
 
Objective-C to Swift - Swift Cloud Workshop 3
Randy Scovil
 
Introduction to Swift 2
Joris Timmerman
 
Swift, a quick overview
Julian Król
 
Custom view
SV.CO
 
Infinum iOS Talks #1 - Swift done right by Ivan Dikic
Infinum
 
Intro toswift1
Jordan Morgan
 
SV-ios-objc-to-swift
Randy Scovil
 
Protocol-Oriented Programming in Swift
Oleksandr Stepanov
 
Programming with Objective-C
Nagendra Ram
 
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
Jonathan Engelsma
 
Swift rocks! #1
Hackraft
 
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 02)
Jonathan Engelsma
 
Protocols promised-land-2
Michele Titolo
 
Developing Swift - Moving towards the future
Pablo Villar
 
Никита Корчагин - Programming Apple iOS with Objective-C
DataArt
 
How would you describe Swift in three words?
Colin Eberhardt
 
Ad

Recently uploaded (20)

PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 

Swift Tutorial Part 2. The complete guide for Swift programming language

  • 1. By: Hossam Ghareeb [email protected] Part 2 The Complete Guide For Programming Language
  • 2. 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
  • 3. 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.
  • 4. Classes ● Student class example
  • 5. 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.
  • 7. 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.
  • 9. 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.
  • 11. 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.
  • 12. 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.
  • 13. 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 =>
  • 15. 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
  • 17. 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
  • 19. 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:
  • 20. 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
  • 21. Type Casting In this example you will see how to use as?
  • 22. 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:
  • 23. 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:
  • 24. 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.
  • 25. 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.
  • 27. 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.
  • 28. Protocols Composition ● If you want a type to conform to multiple protocols use the form protocol<SomeProtocol, AnotherProtocol>
  • 29. Checking For Protocol Conformance ● Use is, as or as? to check for protocol conformance. ● You must mark your protocol with @objc 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.
  • 30. 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 the @objc attribute
  • 31. 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:
  • 33. 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:
  • 34. 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
  • 35. Extension Examples Define new initializers: We will add a new initializer for CGRect , to accept center point, width and height.
  • 36. 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.
  • 37. Extension Examples Define mutating methods: Add methods that modify in the instance itself (mutate it):
  • 38. Extension Examples Protocol adoption with Extension:
  • 39. 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:
  • 40. Generics We will build a stack data structure with generic type. It can be stack of Strings, Ints, ….. or even custom objects.
  • 41. 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
  • 43. Thanks! 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