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
Ad

More Related Content

What's hot (20)

Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
Haitham El-Ghareeb
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
H2Kinfosys
 
What is keyword in c programming
What is keyword in c programmingWhat is keyword in c programming
What is keyword in c programming
Rumman Ansari
 
C# operators
C# operatorsC# operators
C# operators
baabtra.com - No. 1 supplier of quality freshers
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
kapil078
 
Tokens in C++
Tokens in C++Tokens in C++
Tokens in C++
Mahender Boda
 
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
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
C vs c++
C vs c++C vs c++
C vs c++
Gaurav Badhan
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
Kamal Acharya
 
Oops concept in c++ unit 3 -topic 4
Oops concept in c++ unit 3 -topic 4Oops concept in c++ unit 3 -topic 4
Oops concept in c++ unit 3 -topic 4
MOHIT TOMAR
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
Dhrumil Patel
 
C programming tutorial
C programming tutorialC programming tutorial
C programming tutorial
Mohit Saini
 
7.data types in c#
7.data types in c#7.data types in c#
7.data types in c#
Zeeshan Ahmad
 
enums
enumsenums
enums
teach4uin
 
Python-00 | Introduction and installing
Python-00 | Introduction and installingPython-00 | Introduction and installing
Python-00 | Introduction and installing
Mohd Sajjad
 
C programming notes
C programming notesC programming notes
C programming notes
Prof. Dr. K. Adisesha
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
Pushpendra Tyagi
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
H2Kinfosys
 
What is keyword in c programming
What is keyword in c programmingWhat is keyword in c programming
What is keyword in c programming
Rumman Ansari
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
kapil078
 
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
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
Kamal Acharya
 
Oops concept in c++ unit 3 -topic 4
Oops concept in c++ unit 3 -topic 4Oops concept in c++ unit 3 -topic 4
Oops concept in c++ unit 3 -topic 4
MOHIT TOMAR
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
Dhrumil Patel
 
C programming tutorial
C programming tutorialC programming tutorial
C programming tutorial
Mohit Saini
 
Python-00 | Introduction and installing
Python-00 | Introduction and installingPython-00 | Introduction and installing
Python-00 | Introduction and installing
Mohd Sajjad
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
Pushpendra Tyagi
 

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
 
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
 
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdkI os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
政斌 楊
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.
Icalia Labs
 
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
 
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdkI os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
政斌 楊
 
Ad

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

Introduction to Javascript and Typescript.pdf
Introduction to Javascript and Typescript.pdfIntroduction to Javascript and Typescript.pdf
Introduction to Javascript and Typescript.pdf
rony setyawansyah
 
TypeScript.ppt LPU Notes Lecture PPT for 2024
TypeScript.ppt  LPU Notes Lecture PPT for 2024TypeScript.ppt  LPU Notes Lecture PPT for 2024
TypeScript.ppt LPU Notes Lecture PPT for 2024
manveersingh2k05
 
13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript
tayyabbiswas2025
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Viyaan Jhiingade
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
SadhanaParameswaran
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
Vijay Kalyan
 
Airbnb Javascript Style Guide
Airbnb Javascript Style GuideAirbnb Javascript Style Guide
Airbnb Javascript Style Guide
Creative Partners
 
Typescript: Beginner to Advanced
Typescript: Beginner to AdvancedTypescript: Beginner to Advanced
Typescript: Beginner to Advanced
Talentica Software
 
oopm 2.pdf
oopm 2.pdfoopm 2.pdf
oopm 2.pdf
jayeshsoni49
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
Shoaib Ghachi
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
manaswinimysore
 
The advantage of developing with TypeScript
The advantage of developing with TypeScript The advantage of developing with TypeScript
The advantage of developing with TypeScript
Corley S.r.l.
 
AngularConf2015
AngularConf2015AngularConf2015
AngularConf2015
Alessandro Giorgetti
 
7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf
simukondasankananji8
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
Mukesh Kumar
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
Ashiq Uz Zoha
 
01 objective-c session 1
01  objective-c session 101  objective-c session 1
01 objective-c session 1
Amr Elghadban (AmrAngry)
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
Aniruddha Chakrabarti
 
Introduction to Javascript and Typescript.pdf
Introduction to Javascript and Typescript.pdfIntroduction to Javascript and Typescript.pdf
Introduction to Javascript and Typescript.pdf
rony setyawansyah
 
TypeScript.ppt LPU Notes Lecture PPT for 2024
TypeScript.ppt  LPU Notes Lecture PPT for 2024TypeScript.ppt  LPU Notes Lecture PPT for 2024
TypeScript.ppt LPU Notes Lecture PPT for 2024
manveersingh2k05
 
13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript
tayyabbiswas2025
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
Vijay Kalyan
 
Airbnb Javascript Style Guide
Airbnb Javascript Style GuideAirbnb Javascript Style Guide
Airbnb Javascript Style Guide
Creative Partners
 
Typescript: Beginner to Advanced
Typescript: Beginner to AdvancedTypescript: Beginner to Advanced
Typescript: Beginner to Advanced
Talentica Software
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
Shoaib Ghachi
 
The advantage of developing with TypeScript
The advantage of developing with TypeScript The advantage of developing with TypeScript
The advantage of developing with TypeScript
Corley S.r.l.
 
7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf
simukondasankananji8
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
Mukesh Kumar
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
Ashiq Uz Zoha
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
Ad

Recently uploaded (20)

Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Download 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-ActivatedDownload 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-Activated
Web Designer
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
The Elixir Developer - All Things Open
The Elixir Developer - All Things OpenThe Elixir Developer - All Things Open
The Elixir Developer - All Things Open
Carlo Gilmar Padilla Santana
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-RuntimeReinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Natan Silnitsky
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Download 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-ActivatedDownload 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-Activated
Web Designer
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-RuntimeReinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Natan Silnitsky
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 

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

  • 1. By: Hossam Ghareeb hossam.ghareb@gmail.com 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
  翻译: