SlideShare a Scribd company logo
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

KEY
Deriving Scalaz
PDF
Working with Cocoa and Objective-C
PDF
Quick swift tour
PPTX
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
PDF
Introduction to Swift 2
PPT
Intermediate JavaScript
ODP
Scala Reflection & Runtime MetaProgramming
PDF
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
Deriving Scalaz
Working with Cocoa and Objective-C
Quick swift tour
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
Introduction to Swift 2
Intermediate JavaScript
Scala Reflection & Runtime MetaProgramming
OSCON Presentation: Developing High Performance Websites and Modern Apps with...

What's hot (20)

PPTX
25csharp
PDF
Scala jargon cheatsheet
PDF
Scala - core features
PDF
From android/java to swift (3)
PPTX
Practical scalaz
PDF
ppopoff
PDF
Few simple-type-tricks in scala
PDF
Scala: A brief tutorial
PPTX
Scala basic
PDF
Solid and Sustainable Development in Scala
PDF
Miles Sabin Introduction To Scala For Java Developers
PDF
Swift Basics
PDF
Scala cheatsheet
PDF
An Introduction to Scala for Java Developers
PDF
Scala for Java Programmers
PDF
Effective Scala: Programming Patterns
PDF
Nikita Popov "What’s new in PHP 8.0?"
PDF
Scala at HUJI PL Seminar 2008
PPTX
An Introduction to Scala
25csharp
Scala jargon cheatsheet
Scala - core features
From android/java to swift (3)
Practical scalaz
ppopoff
Few simple-type-tricks in scala
Scala: A brief tutorial
Scala basic
Solid and Sustainable Development in Scala
Miles Sabin Introduction To Scala For Java Developers
Swift Basics
Scala cheatsheet
An Introduction to Scala for Java Developers
Scala for Java Programmers
Effective Scala: Programming Patterns
Nikita Popov "What’s new in PHP 8.0?"
Scala at HUJI PL Seminar 2008
An Introduction to Scala
Ad

Similar to Swift as an OOP Language (20)

PDF
Deep Dive Into Swift
PDF
Swift Programming
PDF
Swift Introduction
PDF
An introduction to functional programming with Swift
PDF
Introduction to Swift programming language.
PDF
Cocoa Design Patterns in Swift
PDF
Think sharp, write swift
PDF
Introduction to Swift
PPTX
Dynamic databinding
PDF
Swift, swiftly
PDF
A swift introduction to Swift
PDF
Pooya Khaloo Presentation on IWMC 2015
PDF
Property wrapper and how to use them with mvvm in swift ui i copy
PDF
NSCoder Swift - An Introduction to Swift
PDF
Infinum iOS Talks #1 - Swift done right by Ivan Dikic
PDF
Minimizing Decision Fatigue to Improve Team Productivity
PDF
Swift - the future of iOS app development
PDF
Swift Programming Language
PDF
Swift Tutorial Part 2. The complete guide for Swift programming language
PDF
iOSNeXT.ro - 10 reasons you'll love Swift - Paul Ardeleanu
Deep Dive Into Swift
Swift Programming
Swift Introduction
An introduction to functional programming with Swift
Introduction to Swift programming language.
Cocoa Design Patterns in Swift
Think sharp, write swift
Introduction to Swift
Dynamic databinding
Swift, swiftly
A swift introduction to Swift
Pooya Khaloo Presentation on IWMC 2015
Property wrapper and how to use them with mvvm in swift ui i copy
NSCoder Swift - An Introduction to Swift
Infinum iOS Talks #1 - Swift done right by Ivan Dikic
Minimizing Decision Fatigue to Improve Team Productivity
Swift - the future of iOS app development
Swift Programming Language
Swift Tutorial Part 2. The complete guide for Swift programming language
iOSNeXT.ro - 10 reasons you'll love Swift - Paul Ardeleanu
Ad

Recently uploaded (20)

PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
A Presentation on Artificial Intelligence
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Spectroscopy.pptx food analysis technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
Encapsulation theory and applications.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Approach and Philosophy of On baking technology
Review of recent advances in non-invasive hemoglobin estimation
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
A Presentation on Artificial Intelligence
Mobile App Security Testing_ A Comprehensive Guide.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Spectroscopy.pptx food analysis technology
Big Data Technologies - Introduction.pptx
Encapsulation theory and applications.pdf
The AUB Centre for AI in Media Proposal.docx
A comparative analysis of optical character recognition models for extracting...
Network Security Unit 5.pdf for BCA BBA.
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Assigned Numbers - 2025 - Bluetooth® Document
20250228 LYD VKU AI Blended-Learning.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Advanced methodologies resolving dimensionality complications for autism neur...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
cuic standard and advanced reporting.pdf
Approach and Philosophy of On baking technology

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