SlideShare a Scribd company logo
1 of 41
SWIFT AS AN OOP LANGUAGE 
iOS Development using Swift 
Ahmed Ali
TODAY TOPICS 
• Classes and Structures 
• Properties 
• Methods 
• Access Control 
• Inheritance 
• Initialization 
• Deinitialization 
• Protocols 
• Transitions and View Controller Lifecycle Demo 
Ahmed Ali
CLASSES AND STRUCTURES 
• Both can: 
• Define properties to store values 
• Define methods to provide functionality 
• Define subscripts 
• Define initializers 
• Can be extended (not subclassed, only a class can have a subclass) 
• Conform to protocols 
Ahmed Ali 
ref["key”] anotherRef[1]
CLASSES AND STRUCTURES (CONT) 
• Only classes can: 
• Inherit from another class 
• Define deinit method 
• Type casted 
Ahmed Ali
CLASSES AND STRUCTURES (CONT) 
• Class vs Structure 
• Definition Syntax: 
• Classes passed by reference, 
while structures are passed by 
value. Structures called value 
types for that reason. 
• Create instance: 
class SomeClass 
{ 
} 
struct SomeStruct 
{ 
} 
let someClass = SomeClass() 
let someStruct = SomeStruct() 
Ahmed Ali
PROPERTIES 
• Properties associate values with particular type’s instances. 
• Properties can be a variable or a constant 
• There are two main types of properties: 
• Stored Properties 
• Computed Properties 
Ahmed Ali
• Stored properties just store the values, 
while computed properties compute 
their values. 
• Example of stored properties: 
• No initial value for non optional? 
struct Point 
{ 
var x : Float 
var y : Float 
} 
struct Size 
{ 
var width : Float 
var height : Float 
} 
PROPERTIES (CONT) 
Ahmed Ali
PROPERTIES (CONT) 
• Example of computed properties: 
struct Rect 
{ 
var origin = Point(x: 0, y: 0), size = Size(width: 50, height: 50) 
var center : Point{ 
get{ 
return Point(x: origin.x + (size.width * 0.5), y: origin.y + (size.height * 0.5)) 
} 
set{ 
origin.x = newValue.x - (size.width * 0.5) 
origin.y = newValue.y - (size.height * 0.5) 
} 
} 
} 
Ahmed Ali
PROPERTIES (CONT) 
• Both types of properties are accessible and modifiable in the same manner, using the dot 
syntax. 
• Computed properties calculated every time you access them. 
//If a structure reference is defined as a constant, we will not be able to change 
any of its properties 
var rect = Rect() 
let centerPoint = rect.center 
let origin = rect.origin 
//modifying their values 
rect.origin.x = 50 
rect.center = Point(x: 100, y: 100) 
Ahmed Ali
PROPERTIES (CONT) 
• Property observers: 
• didSet, willSet 
• Syntax: 
struct Point 
{ 
var x : Float{ 
didSet{ 
println("The value of x has been changed from (oldValue) to (x)") 
} 
willSet{ 
println("The value of x has been changed from (x) to (newValue)") 
} 
} 
var y : Float 
} 
Ahmed Ali
METHODS 
• Methods are used to provide functionality associated with a specific type. 
• Methods can have: 
• One or more parameter. 
• A return value of any type. 
• Can have external parameter names, for better readability. 
• Definition Syntax: 
class SomeClass{ 
func methodName(param1 : String) -> Int? 
{ 
//countElements is a global function that returns the string length 
return countElements(param1) 
} 
} 
Ahmed Ali
METHODS (CONT) 
• External parameter name, promising better readability for your method users. 
• Method call without external parameter names: 
let view = View() 
Animator.moveView(view, Point(0, 0), Point(50, 50)) 
Ahmed Ali
METHODS (CONT) 
• Method call with external parameter names: 
let view = View() 
Animator.moveView(view, fromPoint: Point(x:0, y:0), toPoint: Point(x: 50, y: 50)) 
Ahmed Ali
METHODS (CONT) 
• Defining parameter external name: 
struct Math 
{ 
static func powerOfNumber(baseNumber: Int, toPower power: UInt) -> Int 
{ 
var total = 0 
for i in 2 ... power 
{ 
total += (baseNumber * baseNumber) 
} 
return total 
} 
} 
let value = Math.powerOfNumber(2, toPower: 3) 
Ahmed Ali
METHODS (CONT) 
• You can override this external name behavior if it does not make sense: 
struct Math 
{ 
static func powerOfNumber(baseNumber: Int, _ power: UInt) -> Int 
{ 
var total = 0 
for i in 2 ... power 
{ 
total += (baseNumber * baseNumber) 
} 
return total 
} 
} 
let value = Math.powerOfNumber(2, 3) 
Ahmed Ali
METHODS (CONT) 
• You can create static methods which can be access without the need to create an 
instance. 
• Example: 
struct Math 
{ 
static func add(x : Int, _ y : Int) ->Int 
{ 
return x + y 
} 
} 
println("5 + 6 = (Math.add(5, 6))") 
Ahmed Ali
METHODS (CONT) 
• For value types, you can not change any property inside any method. 
• If a method will change any property value, it must be marked as a mutating method. 
• Mutating method can not be called on any constant reference. 
• Example: 
struct SomeStruct{ 
var property : String 
mutating func changeProperty(newValue : String) 
{ 
property = newValue 
} 
} 
let s = SomeStruct(property: "value") 
//invalid because s is a constant 
s.changeProperty("new value") 
Ahmed Ali
ACCESS CONTROL 
Modules vs Source Files 
Ahmed Ali
ACCESS CONTROL (CONT) 
• Access Levels 
• Public: Accessible everywhere. 
• Internal: Accessible for any source code file in defining module. 
• Private: Accessible only in the same source code file. 
• Internal is the default access level. 
Ahmed Ali
ACCESS CONTROL (CONT) 
• Syntax: 
public class SomeClass 
{ 
private var myVar = "My Var Value" 
internal var myInt = 5 
public func calc() -> String 
{ 
return "(myVar) => (myInt)" 
} 
} 
Ahmed Ali
INHERITANCE 
• No universal base class that all other classes inherit from. 
• Any class who has no super class, is known to be a base class. 
• You can override super class methods and computed properties using the override 
keyword. 
• You can not override stored properties of super class, but you can observe them. 
Ahmed Ali
INHERITANCE (CONT) 
• Base class example: 
class BaseClass 
{ 
var computedProperty : String{ 
get{ return ”BaseClass property” } set{ 
println(newValue) 
} 
} 
func printClassName() 
{ 
println("BaseClass") 
} 
} 
Ahmed Ali
INHERITANCE (CONT) 
• Inheritance example: 
class Subclass : BaseClass 
{ 
} 
Ahmed Ali
INHERITANCE (CONT) 
• Overriding computed property example: 
class Subclass : BaseClass 
{ 
override var computedProperty : String 
{ 
get{ 
return "Subclass property" 
} 
set{ 
println("Setting the property in the subclass") 
} 
} 
} 
Ahmed Ali
INHERITANCE (CONT) 
• Overriding a method example: 
class Subclass : BaseClass 
{ 
override func printClassName() 
{ 
//you can also call the original method 
//which were defined in the super class 
super.printClassName() 
println("Subclass") 
} 
} 
Ahmed Ali
INITIALIZATION 
• Initialization is the process of creating a new instance. 
• Mainly used to set non-optional properties’ values and any initial setup. 
• The initialization process can not be completed while any non-optional properties still 
have no value. 
• Implementation is done through special methods called initializers. 
Ahmed Ali
INITIALIZATION - INITIALIZERS 
• An initializer is a normal method, with little different syntax. 
• Initializer method is always called “init” 
• You don’t write the “func” keyword before the initializer. 
• Initializers always return nothing. 
• Can take zero or more parameters. 
• Class can have zero or more initializers. 
• An initializer is required if any of your non-optional properties have no default value. 
Ahmed Ali
INITIALIZATION – INITIALIZERS (CONT) 
• Initializer example: 
class SomeClass 
{ 
//because we do not provide the property's initial value here 
//we must provide its value in the initializer 
var strProperty : String 
init() 
{ 
//If you have any property observers, they will not be called during the initial value 
assignment 
strProperty = "Initial value" 
} 
} 
Ahmed Ali
INITIALIZATION – INITIALIZERS (CONT) 
• You can create custom initializer that takes one or more parameter. 
• Unlike methods, all initializer’s parameters have external names by default. 
• Example: 
class SomeClass 
{ 
var strProperty : String 
init(strProperty: String) 
{ 
self.strProperty = strProperty 
} 
} 
Ahmed Ali
INITIALIZATION – INITIALIZERS (CONT) 
• Default initializer (that takes no parameters) is automatically available if and only if: 
1. All your non-optional properties have default values and you did not create any 
initializers at all. 
• Constant property value can be modified in any initializer. However, you can not modify 
super class’s constant property in a subclass initializer. 
Ahmed Ali
INITIALIZATION – INITIALIZERS (CONT) 
• Create an instance the default initializer: 
let someClass = SomeClass() 
• Create an instance with custom initializer: 
let someClass = SomeClass(strProperty: "String value") 
Ahmed Ali
INITIALIZATION – INITIALIZERS (CONT) 
• In structure types, if you have not defined any initializer, a member -wise initializer is 
automatically created for you. 
• Example: 
struct Point 
{ 
var x : Float 
var y : Float 
} 
Now you can create instances of the Point type using its auto-created member-wise initializer 
as follows: 
let point = Point(x: 15, y: 20) 
Ahmed Ali
INITIALIZATION – INITIALIZERS (CONT) 
Designated Convenience 
• Provides a more convenience 
initializer. 
• Must end up calling a designated 
initializer. 
• Syntax - add “conveniece” keyword 
before “init”. Example: 
convenience init() 
{ 
} 
• All non-optional properties’ values are 
assigned before it is finished. 
• For classes, it must call the super 
class designated initializer if defined in 
a subclass. 
• Syntax - any initializer you defined 
before with “init” is a designated 
initializer. 
Ahmed Ali 
Types of initializers: designated and convenience.
INITIALIZATION – INITIALIZERS (CONT) 
class BaseClass 
{ 
var str : String 
var str2 : String 
init(str : String, str2: String) 
{ 
self.str = str 
self.str2 = str2 
} 
convenience init(str: String) 
{ 
self.init(str: str, str2: "String 2") 
} 
} 
class Subclass : BaseClass 
{ 
var substr : String 
init(substr : String) 
{ 
self.substr = substr 
super.init(str:substr, str2: "none") 
} 
} 
Ahmed Ali 
Example:
DEINITIALIZATION 
• Deinitlization is the process of making any final clean-up before removing a class’s 
instance from the memory. 
• You just need to implement a special method called deinit which takes no parameters and 
returns nothing. 
• Example: 
deinit{ 
//Your clean up code goes here 
} 
Ahmed Ali
PROTOCOLS 
• A protocol defines set of properties and methods, not their implementation. 
• Any class, structure or enumeration can conform to any number of protocols. 
• When a type is said to be conforming to a protocol, it means: this type provides the actual 
implementation for that protocol. 
• Definition syntax: 
protocol SomeProtocol 
{ 
//read and write property 
var neededProperty : String {get set} 
//read-only property 
var anotherProperty : String {get} 
func requiredMethod() -> (String, String) 
} 
Ahmed Ali
PROTOCOLS 
• Syntax for defining a type which conforms to a protocol: 
struct SomeStruct : SomeProtocol{ 
var neededProperty : String 
var anotherProperty : String 
func requiredMethod() -> (String, String) { 
return ("V1", "V2") 
} 
} 
Ahmed Ali
PROTOCOLS 
• If the type is a class, and it also subclass another class, the super class name comes first 
in the list. 
• Example: 
class Subclass : BaseClass, SomeProtocol, AnotherProtocol{ 
var neededProperty : String 
var anotherProperty : String 
func requiredMethod() -> (String, String) { 
return ("V1", "V2") 
} 
} 
Ahmed Ali
PROTOCOLS 
• Protocols can be used as a type. That is, you can define any reference with the type of a 
protocol instead of a concrete type. 
• Example: 
struct SomeStruct 
{ 
var property : SomeProtocol 
func method(param1 : AnotherProtocol) 
{ 
} 
} 
Ahmed Ali
PROTOCOLS 
• You can also define a reference to be any type that conforms to more than one protocol 
• Example: 
struct SomeStruct{ 
var property : protocol<SomeProtocol, AnotherProtocol> 
} 
Ahmed Ali
Ahmed Ali 
Transitions and View Controller Lifecycle Demo

More Related Content

What's hot

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
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scalaRuslan Shevchenko
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scalascalaconfjp
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming PatternsVasil Remeniuk
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to ScalaBrent Lemons
 

What's hot (20)

25csharp
25csharp25csharp
25csharp
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
ppopoff
ppopoffppopoff
ppopoff
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
Js
JsJs
Js
 
Scala: A brief tutorial
Scala: A brief tutorialScala: A brief tutorial
Scala: A brief tutorial
 
Scala basic
Scala basicScala basic
Scala basic
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Swift Basics
Swift BasicsSwift Basics
Swift Basics
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming Patterns
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to Scala
 

Similar to Swift as an OOP Language (20)

CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
C#2
C#2C#2
C#2
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Oops
OopsOops
Oops
 
Constructor
ConstructorConstructor
Constructor
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
C++ - Constructors,Destructors, Operator overloading and Type conversion
C++ - Constructors,Destructors, Operator overloading and Type conversionC++ - Constructors,Destructors, Operator overloading and Type conversion
C++ - Constructors,Destructors, Operator overloading and Type conversion
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
CSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionCSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+Reflection
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
25c
25c25c
25c
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
iOS development using Swift - Swift Basics (2)
iOS development using Swift - Swift Basics (2)iOS development using Swift - Swift Basics (2)
iOS development using Swift - Swift Basics (2)
 
Lesson3
Lesson3Lesson3
Lesson3
 
Lesson3
Lesson3Lesson3
Lesson3
 
Java
Java Java
Java
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Unit ii
Unit iiUnit ii
Unit ii
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 

Recently uploaded (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

Swift as an OOP Language

  • 1. SWIFT AS AN OOP LANGUAGE iOS Development using Swift Ahmed Ali
  • 2. TODAY TOPICS • Classes and Structures • Properties • Methods • Access Control • Inheritance • Initialization • Deinitialization • Protocols • Transitions and View Controller Lifecycle Demo Ahmed Ali
  • 3. CLASSES AND STRUCTURES • Both can: • Define properties to store values • Define methods to provide functionality • Define subscripts • Define initializers • Can be extended (not subclassed, only a class can have a subclass) • Conform to protocols Ahmed Ali ref["key”] anotherRef[1]
  • 4. CLASSES AND STRUCTURES (CONT) • Only classes can: • Inherit from another class • Define deinit method • Type casted Ahmed Ali
  • 5. CLASSES AND STRUCTURES (CONT) • Class vs Structure • Definition Syntax: • Classes passed by reference, while structures are passed by value. Structures called value types for that reason. • Create instance: class SomeClass { } struct SomeStruct { } let someClass = SomeClass() let someStruct = SomeStruct() Ahmed Ali
  • 6. PROPERTIES • Properties associate values with particular type’s instances. • Properties can be a variable or a constant • There are two main types of properties: • Stored Properties • Computed Properties Ahmed Ali
  • 7. • Stored properties just store the values, while computed properties compute their values. • Example of stored properties: • No initial value for non optional? struct Point { var x : Float var y : Float } struct Size { var width : Float var height : Float } PROPERTIES (CONT) Ahmed Ali
  • 8. PROPERTIES (CONT) • Example of computed properties: struct Rect { var origin = Point(x: 0, y: 0), size = Size(width: 50, height: 50) var center : Point{ get{ return Point(x: origin.x + (size.width * 0.5), y: origin.y + (size.height * 0.5)) } set{ origin.x = newValue.x - (size.width * 0.5) origin.y = newValue.y - (size.height * 0.5) } } } Ahmed Ali
  • 9. PROPERTIES (CONT) • Both types of properties are accessible and modifiable in the same manner, using the dot syntax. • Computed properties calculated every time you access them. //If a structure reference is defined as a constant, we will not be able to change any of its properties var rect = Rect() let centerPoint = rect.center let origin = rect.origin //modifying their values rect.origin.x = 50 rect.center = Point(x: 100, y: 100) Ahmed Ali
  • 10. PROPERTIES (CONT) • Property observers: • didSet, willSet • Syntax: struct Point { var x : Float{ didSet{ println("The value of x has been changed from (oldValue) to (x)") } willSet{ println("The value of x has been changed from (x) to (newValue)") } } var y : Float } Ahmed Ali
  • 11. METHODS • Methods are used to provide functionality associated with a specific type. • Methods can have: • One or more parameter. • A return value of any type. • Can have external parameter names, for better readability. • Definition Syntax: class SomeClass{ func methodName(param1 : String) -> Int? { //countElements is a global function that returns the string length return countElements(param1) } } Ahmed Ali
  • 12. METHODS (CONT) • External parameter name, promising better readability for your method users. • Method call without external parameter names: let view = View() Animator.moveView(view, Point(0, 0), Point(50, 50)) Ahmed Ali
  • 13. METHODS (CONT) • Method call with external parameter names: let view = View() Animator.moveView(view, fromPoint: Point(x:0, y:0), toPoint: Point(x: 50, y: 50)) Ahmed Ali
  • 14. METHODS (CONT) • Defining parameter external name: struct Math { static func powerOfNumber(baseNumber: Int, toPower power: UInt) -> Int { var total = 0 for i in 2 ... power { total += (baseNumber * baseNumber) } return total } } let value = Math.powerOfNumber(2, toPower: 3) Ahmed Ali
  • 15. METHODS (CONT) • You can override this external name behavior if it does not make sense: struct Math { static func powerOfNumber(baseNumber: Int, _ power: UInt) -> Int { var total = 0 for i in 2 ... power { total += (baseNumber * baseNumber) } return total } } let value = Math.powerOfNumber(2, 3) Ahmed Ali
  • 16. METHODS (CONT) • You can create static methods which can be access without the need to create an instance. • Example: struct Math { static func add(x : Int, _ y : Int) ->Int { return x + y } } println("5 + 6 = (Math.add(5, 6))") Ahmed Ali
  • 17. METHODS (CONT) • For value types, you can not change any property inside any method. • If a method will change any property value, it must be marked as a mutating method. • Mutating method can not be called on any constant reference. • Example: struct SomeStruct{ var property : String mutating func changeProperty(newValue : String) { property = newValue } } let s = SomeStruct(property: "value") //invalid because s is a constant s.changeProperty("new value") Ahmed Ali
  • 18. ACCESS CONTROL Modules vs Source Files Ahmed Ali
  • 19. ACCESS CONTROL (CONT) • Access Levels • Public: Accessible everywhere. • Internal: Accessible for any source code file in defining module. • Private: Accessible only in the same source code file. • Internal is the default access level. Ahmed Ali
  • 20. ACCESS CONTROL (CONT) • Syntax: public class SomeClass { private var myVar = "My Var Value" internal var myInt = 5 public func calc() -> String { return "(myVar) => (myInt)" } } Ahmed Ali
  • 21. INHERITANCE • No universal base class that all other classes inherit from. • Any class who has no super class, is known to be a base class. • You can override super class methods and computed properties using the override keyword. • You can not override stored properties of super class, but you can observe them. Ahmed Ali
  • 22. INHERITANCE (CONT) • Base class example: class BaseClass { var computedProperty : String{ get{ return ”BaseClass property” } set{ println(newValue) } } func printClassName() { println("BaseClass") } } Ahmed Ali
  • 23. INHERITANCE (CONT) • Inheritance example: class Subclass : BaseClass { } Ahmed Ali
  • 24. INHERITANCE (CONT) • Overriding computed property example: class Subclass : BaseClass { override var computedProperty : String { get{ return "Subclass property" } set{ println("Setting the property in the subclass") } } } Ahmed Ali
  • 25. INHERITANCE (CONT) • Overriding a method example: class Subclass : BaseClass { override func printClassName() { //you can also call the original method //which were defined in the super class super.printClassName() println("Subclass") } } Ahmed Ali
  • 26. INITIALIZATION • Initialization is the process of creating a new instance. • Mainly used to set non-optional properties’ values and any initial setup. • The initialization process can not be completed while any non-optional properties still have no value. • Implementation is done through special methods called initializers. Ahmed Ali
  • 27. INITIALIZATION - INITIALIZERS • An initializer is a normal method, with little different syntax. • Initializer method is always called “init” • You don’t write the “func” keyword before the initializer. • Initializers always return nothing. • Can take zero or more parameters. • Class can have zero or more initializers. • An initializer is required if any of your non-optional properties have no default value. Ahmed Ali
  • 28. INITIALIZATION – INITIALIZERS (CONT) • Initializer example: class SomeClass { //because we do not provide the property's initial value here //we must provide its value in the initializer var strProperty : String init() { //If you have any property observers, they will not be called during the initial value assignment strProperty = "Initial value" } } Ahmed Ali
  • 29. INITIALIZATION – INITIALIZERS (CONT) • You can create custom initializer that takes one or more parameter. • Unlike methods, all initializer’s parameters have external names by default. • Example: class SomeClass { var strProperty : String init(strProperty: String) { self.strProperty = strProperty } } Ahmed Ali
  • 30. INITIALIZATION – INITIALIZERS (CONT) • Default initializer (that takes no parameters) is automatically available if and only if: 1. All your non-optional properties have default values and you did not create any initializers at all. • Constant property value can be modified in any initializer. However, you can not modify super class’s constant property in a subclass initializer. Ahmed Ali
  • 31. INITIALIZATION – INITIALIZERS (CONT) • Create an instance the default initializer: let someClass = SomeClass() • Create an instance with custom initializer: let someClass = SomeClass(strProperty: "String value") Ahmed Ali
  • 32. INITIALIZATION – INITIALIZERS (CONT) • In structure types, if you have not defined any initializer, a member -wise initializer is automatically created for you. • Example: struct Point { var x : Float var y : Float } Now you can create instances of the Point type using its auto-created member-wise initializer as follows: let point = Point(x: 15, y: 20) Ahmed Ali
  • 33. INITIALIZATION – INITIALIZERS (CONT) Designated Convenience • Provides a more convenience initializer. • Must end up calling a designated initializer. • Syntax - add “conveniece” keyword before “init”. Example: convenience init() { } • All non-optional properties’ values are assigned before it is finished. • For classes, it must call the super class designated initializer if defined in a subclass. • Syntax - any initializer you defined before with “init” is a designated initializer. Ahmed Ali Types of initializers: designated and convenience.
  • 34. INITIALIZATION – INITIALIZERS (CONT) class BaseClass { var str : String var str2 : String init(str : String, str2: String) { self.str = str self.str2 = str2 } convenience init(str: String) { self.init(str: str, str2: "String 2") } } class Subclass : BaseClass { var substr : String init(substr : String) { self.substr = substr super.init(str:substr, str2: "none") } } Ahmed Ali Example:
  • 35. DEINITIALIZATION • Deinitlization is the process of making any final clean-up before removing a class’s instance from the memory. • You just need to implement a special method called deinit which takes no parameters and returns nothing. • Example: deinit{ //Your clean up code goes here } Ahmed Ali
  • 36. PROTOCOLS • A protocol defines set of properties and methods, not their implementation. • Any class, structure or enumeration can conform to any number of protocols. • When a type is said to be conforming to a protocol, it means: this type provides the actual implementation for that protocol. • Definition syntax: protocol SomeProtocol { //read and write property var neededProperty : String {get set} //read-only property var anotherProperty : String {get} func requiredMethod() -> (String, String) } Ahmed Ali
  • 37. PROTOCOLS • Syntax for defining a type which conforms to a protocol: struct SomeStruct : SomeProtocol{ var neededProperty : String var anotherProperty : String func requiredMethod() -> (String, String) { return ("V1", "V2") } } Ahmed Ali
  • 38. PROTOCOLS • If the type is a class, and it also subclass another class, the super class name comes first in the list. • Example: class Subclass : BaseClass, SomeProtocol, AnotherProtocol{ var neededProperty : String var anotherProperty : String func requiredMethod() -> (String, String) { return ("V1", "V2") } } Ahmed Ali
  • 39. PROTOCOLS • Protocols can be used as a type. That is, you can define any reference with the type of a protocol instead of a concrete type. • Example: struct SomeStruct { var property : SomeProtocol func method(param1 : AnotherProtocol) { } } Ahmed Ali
  • 40. PROTOCOLS • You can also define a reference to be any type that conforms to more than one protocol • Example: struct SomeStruct{ var property : protocol<SomeProtocol, AnotherProtocol> } Ahmed Ali
  • 41. Ahmed Ali Transitions and View Controller Lifecycle Demo