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)

Java variable types
Java variable typesJava variable types
Java variable types
Soba Arjun
 
Datatype
DatatypeDatatype
Datatype
baran19901990
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Higher Order Component React
Higher Order Component ReactHigher Order Component React
Higher Order Component React
Heber Silva
 
Data types in java
Data types in javaData types in java
Data types in java
HarshitaAshwani
 
Control structures IN SWIFT
Control structures IN SWIFTControl structures IN SWIFT
Control structures IN SWIFT
LOVELY PROFESSIONAL UNIVERSITY
 
C# Overriding
C# OverridingC# Overriding
C# Overriding
Prem Kumar Badri
 
Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
C Language
C LanguageC Language
C Language
Aakash Singh
 
Basics of oops concept
Basics of oops conceptBasics of oops concept
Basics of oops concept
DINESH KUMAR ARIVARASAN
 
SWE-401 - 2. Software Development life cycle (SDLC)
SWE-401 - 2. Software Development life cycle (SDLC)SWE-401 - 2. Software Development life cycle (SDLC)
SWE-401 - 2. Software Development life cycle (SDLC)
ghayour abbas
 
Java features
Java  features Java  features
Java features
Madishetty Prathibha
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
Cihad Horuzoğlu
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
Dr.Neeraj Kumar Pandey
 
Inheritance
InheritanceInheritance
Inheritance
Pranali Chaudhari
 
Data types IN JAVA
Data types IN JAVAData types IN JAVA
Data types IN JAVA
garishma bhatia
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
ABHISHEK fulwadhwa
 
Strings in java
Strings in javaStrings in java
Strings in java
Kuppusamy P
 
Word Dictionary - Software Development Project 1
Word Dictionary - Software Development Project 1 Word Dictionary - Software Development Project 1
Word Dictionary - Software Development Project 1
Tasnim Ara Islam
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
Mohamed Essam
 

Viewers also liked (20)

Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.
Icalia Labs
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
Natasha Murashev
 
Ieeepro techno solutions ieee dotnet project - privacy-preserving multi-keyw...
Ieeepro techno solutions  ieee dotnet project - privacy-preserving multi-keyw...Ieeepro techno solutions  ieee dotnet project - privacy-preserving multi-keyw...
Ieeepro techno solutions ieee dotnet project - privacy-preserving multi-keyw...
ASAITHAMBIRAJAA
 
Swift-Programming Part 1
Swift-Programming Part 1Swift-Programming Part 1
Swift-Programming Part 1
Mindfire Solutions
 
iOS 10 & XCode 8, Swift 3.0 features and changes
iOS 10 & XCode 8, Swift 3.0 features and changesiOS 10 & XCode 8, Swift 3.0 features and changes
iOS 10 & XCode 8, Swift 3.0 features and changes
Manjula Jonnalagadda
 
What's new in Swift 3
What's new in Swift 3What's new in Swift 3
What's new in Swift 3
Marcio Klepacz
 
Swift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extensionSwift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extension
Kwang Woo NAM
 
Swift 3
Swift   3Swift   3
Swift 3
Michael Shrove
 
Swift 3 Programming for iOS : Enumeration
Swift 3 Programming for iOS : EnumerationSwift 3 Programming for iOS : Enumeration
Swift 3 Programming for iOS : Enumeration
Kwang Woo NAM
 
The Swift Programming Language with iOS App
The Swift Programming Language with iOS AppThe Swift Programming Language with iOS App
The Swift Programming Language with iOS App
Mindfire Solutions
 
iOSMumbai Meetup Keynote
iOSMumbai Meetup KeynoteiOSMumbai Meetup Keynote
iOSMumbai Meetup Keynote
Glimpse Analytics
 
Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app development
openak
 
Medidata Customer Only Event - Global Symposium Highlights
Medidata Customer Only Event - Global Symposium HighlightsMedidata Customer Only Event - Global Symposium Highlights
Medidata Customer Only Event - Global Symposium Highlights
Donna Locke
 
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Jsm2013,598,sweitzer,randomization metrics,v2,aug08Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Dennis Sweitzer
 
Medidata AMUG Meeting / Presentation 2013
Medidata AMUG Meeting / Presentation 2013Medidata AMUG Meeting / Presentation 2013
Medidata AMUG Meeting / Presentation 2013
Brock Heinz
 
Tools, Frameworks, & Swift for iOS
Tools, Frameworks, & Swift for iOSTools, Frameworks, & Swift for iOS
Tools, Frameworks, & Swift for iOS
Teri Grossheim
 
Medidata Rave Coder
Medidata Rave CoderMedidata Rave Coder
Medidata Rave Coder
Nikolay Rusev
 
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
Jonathan Engelsma
 
Beginning iOS Development with Swift
Beginning iOS Development with SwiftBeginning iOS Development with Swift
Beginning iOS Development with Swift
TurnToTech
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.
Icalia Labs
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 
Ieeepro techno solutions ieee dotnet project - privacy-preserving multi-keyw...
Ieeepro techno solutions  ieee dotnet project - privacy-preserving multi-keyw...Ieeepro techno solutions  ieee dotnet project - privacy-preserving multi-keyw...
Ieeepro techno solutions ieee dotnet project - privacy-preserving multi-keyw...
ASAITHAMBIRAJAA
 
iOS 10 & XCode 8, Swift 3.0 features and changes
iOS 10 & XCode 8, Swift 3.0 features and changesiOS 10 & XCode 8, Swift 3.0 features and changes
iOS 10 & XCode 8, Swift 3.0 features and changes
Manjula Jonnalagadda
 
Swift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extensionSwift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extension
Kwang Woo NAM
 
Swift 3 Programming for iOS : Enumeration
Swift 3 Programming for iOS : EnumerationSwift 3 Programming for iOS : Enumeration
Swift 3 Programming for iOS : Enumeration
Kwang Woo NAM
 
The Swift Programming Language with iOS App
The Swift Programming Language with iOS AppThe Swift Programming Language with iOS App
The Swift Programming Language with iOS App
Mindfire Solutions
 
Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app development
openak
 
Medidata Customer Only Event - Global Symposium Highlights
Medidata Customer Only Event - Global Symposium HighlightsMedidata Customer Only Event - Global Symposium Highlights
Medidata Customer Only Event - Global Symposium Highlights
Donna Locke
 
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Jsm2013,598,sweitzer,randomization metrics,v2,aug08Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Jsm2013,598,sweitzer,randomization metrics,v2,aug08
Dennis Sweitzer
 
Medidata AMUG Meeting / Presentation 2013
Medidata AMUG Meeting / Presentation 2013Medidata AMUG Meeting / Presentation 2013
Medidata AMUG Meeting / Presentation 2013
Brock Heinz
 
Tools, Frameworks, & Swift for iOS
Tools, Frameworks, & Swift for iOSTools, Frameworks, & Swift for iOS
Tools, Frameworks, & Swift for iOS
Teri Grossheim
 
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
Jonathan Engelsma
 
Beginning iOS Development with Swift
Beginning iOS Development with SwiftBeginning iOS Development with Swift
Beginning iOS Development with Swift
TurnToTech
 
Ad

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

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

Recently uploaded (20)

Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Migrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right WayMigrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right Way
Alexander (Alex) Komyagin
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 

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