SlideShare a Scribd company logo
1
Swift in depth
Presenter: Waseem Ahmad, Mindfire Solutions
Date: 18/02/2015
What we discussed
Presenter: Waseem Ahmad, Mindfire Solutions
What is Swift?
Variable/Constants
String/Character Interpolation
Array and Dictionary
Loops
Optionals, Unwrapping an Optional
Functions
Tuples
Classes
Properties
What we will Learn Today
Presenter: Waseem Ahmad, Mindfire Solutions
- Closures
- Structures
- Enum
- Memory Management
- Extensions
Closures
To an Objective-C developer, a closure is Swift’s equivalent of blocks.
A formal definition should be that Swift closures are self-contained blocks of
functionality that can be passed around and used in your code.
Intuitively, a closure is a kind of anonymous, nested functions. It’s a chunk
of functionality that can be passed around and used in your code.
Presenter: Waseem Ahmad, Mindfire Solutions
Swift closures syntax
To define one, you’d write something like this:
{ (parameters) -> return_type in
// block body
// write code here
}
{(op1: Double, op2: Double) -> Double in
return op1 + op2
}
Presenter: Waseem Ahmad, Mindfire Solutions
Type Inference
{(op1, op2) in
return op1 + op2
}
Presenter: Waseem Ahmad, Mindfire Solutions
Implicit Return
{(op1, op2) in op1 + op2}
Implicit Arguments
performOperation({$0 + $1})
Presenter: Waseem Ahmad, Mindfire Solutions
Trailing Closures
performOperation() {$0 - $1}
Some Closures Definition
As a variable:
var closureName: (parameterTypes) -> (returnType)
As a type alias:
typealias closureType = (parameterTypes) -> (returnType)
As a function parameter:
array.sort({ (item1: Int, item2: Int) -> Bool in return item1 < item2 })
Presenter: Waseem Ahmad, Mindfire Solutions
Structure
Classes and structures have a similar definition syntax. We introduce classes with the
class keyword and structures with the struct keyword. Both place their entire
definition within a pair of braces:
class SomeClass {
// class definition goes here
}
struct SomeStructure {
// structure definition goes here
}
Presenter: Waseem Ahmad, Mindfire Solutions
Structure Declaration
struct Point {
var x, y: Double
}
struct Size {
var width, height: Double
}
struct Rect {
var origin: Point
var size: Size
}
var point = Point(x: 0.0, y: 0.0)
var size = Size(width: 640.0, height: 480.0)
var rect = Rect(origin: point, size: size)
Presenter: Waseem Ahmad, Mindfire Solutions
Swift Structure
Swift classes and structures are much closer in functionality than in other languages.
- We can define method inside the structure.
- We can define property inside the structure.
Presenter: Waseem Ahmad, Mindfire Solutions
Define properties
struct Rect {
var origin: Point
var size: Size
var area: Double {
return size.width * size.height
}
}
Presenter: Waseem Ahmad, Mindfire Solutions
Define methods
struct Rect {
var origin: Point
var size: Size
var area: Double {
return size.width * size.height
}
func isBiggerThanRect(other: Rect) -> Bool {
return self.area > other.area
}
Presenter: Waseem Ahmad, Mindfire Solutions
Difference between class and struct
- Structures cannot Inherit from other types.
- Class Instances are Passed by Reference (Reference Type). “Unlike value types,
reference types are not copied when they are assigned to a variable or constant, or
when they are passed to a function.”
- Structures are Passed by Value (Value Type) “A value type is a type whose value is
copied when it is assigned to a variable or constant, or when it is passed to a
function.”
- Structures cannot have multiple references to the same instance
- Structures do not have deinitializers.
Presenter: Waseem Ahmad, Mindfire Solutions
Mutating a Structure
struct Point {
var x, y: Double
mutating func moveToTheRightBy(dx: Double) {
x += dx
}
}
Presenter: Waseem Ahmad, Mindfire Solutions
Enum
An enumeration defines a common type for a group of related values.
As you are familiar with C, Objective C, you know that C, Objective C
enumerations assign related names to a set of integer values.
Enumerations in Swift are much more flexible, and do not have to provide a
value for each member of the enumeration. the value can be a string, a
character, or a value of any integer or floating-point type.
Presenter: Waseem Ahmad, Mindfire Solutions
Enum Declaration
enum CompassPoint {
case North
case South
case East
case West
}
var directionToHead = CompassPoint.West
Unlike C and Objective-C, Swift enumeration members are not assigned a
default integer value when they are created.
In the CompassPoint example above, North, South, East and West do not
implicitly equal 0, 1, 2 and 3. Instead, the different enumeration members are
fully-fledged values in their own right, with an explicitly-defined type of
CompassPoint
Presenter: Waseem Ahmad, Mindfire Solutions
Enum and row value
enum Planet : Int {
case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn
}
let earthsOrder = Planet.Earth.rawValue
// earthsOrder is 3
let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet is of type Planet? and equals Planet.Uranus
enum ASCIIControlCharacter: Character {
case Tab = "t"
case LineFeed = "n"
case CarriageReturn = "r"
}
Presenter: Waseem Ahmad, Mindfire Solutions
Enumerations: Associated Values
enum TrainStatus {
case OnTime
case Delayed(Int)
}
var status = TrainStatus.OnTime
// status is inferred to be a TrainStatus
status = .Delayed(42)
Presenter: Waseem Ahmad, Mindfire Solutions
Enumerations: Properties
enum TrainStatus {
case OnTime, Delayed(Int)
init() {
self = OnTime
}
var description: String {
switch self {
case OnTime:
return "on time"
case Delayed(let minutes):
return "delayed by (minutes) minute(s)”
}
}
}
Presenter: Waseem Ahmad, Mindfire Solutions
Enumerations: Properties
var status = TrainStatus()
println("The train is (status.description)")
// The train is on time
status = .Delayed(42)
println("The train is now (status.description)")
// The train is now delayed by 42 minute(s)
Presenter: Waseem Ahmad, Mindfire Solutions
Memory Management
-Swift uses Automatic Reference Counting (ARC) to track and manage your
app’s memory usage.
-ARC requires information about the relationships between parts of your code
in order to manage memory.
-Reference counting only applies to instances of classes. Structures and
enumerations are value types, not reference types, and are not stored and
passed by reference.
Presenter: Waseem Ahmad, Mindfire Solutions
How ARC Works
-Every time you create a new instance of a class, ARC allocates a chunk of
memory to store information about that instance. Something like book
keeping.
-Additionally, when an instance is no longer needed, ARC frees up the memory
used by that instance.
-Reference counting only applies to instances of classes. Structures and
enumerations are value types, not reference types, and are not stored and
passed by reference.
Presenter: Waseem Ahmad, Mindfire Solutions
How ARC Works
class Person {
let name: String
init(name: String) {
self.name = name
}
deinit {
// prints "John Appleseed is being deinitialized"
}
}
var reference1: Person(name: "John Appleseed")
Presenter: Waseem Ahmad, Mindfire Solutions
How ARC Works
var reference2: Person?
var reference3: Person?
If you assign the same Person instance to two more variables, two more
strong references to that instance are established:
reference2 = reference1
reference3 = reference1
There are now three strong references to this single Person instance.
Presenter: Waseem Ahmad, Mindfire Solutions
How ARC Works
reference1 = nil
reference2 = nil
ARC does not deallocate the Person instance until the third and final strong
reference is broken, at which point it is clear that you are no longer using the
Person instance:
reference3 = nil
// prints "John Appleseed is being deinitialized"
Presenter: Waseem Ahmad, Mindfire Solutions
Strong Reference Cycles
In the examples, ARC is able to track the number of references to the new
Person instance you create and to deallocate that Person instance when it is
no longer needed.
However, it is possible to write code in which an instance of a class never gets
to a point where it has zero strong references.
This can happen if two class instances hold a strong reference to each other,
such that each instance keeps the other alive. This is known as a strong
reference cycle.
Presenter: Waseem Ahmad, Mindfire Solutions
Strong Reference Cycles
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { println("(name) is being deinitialized") }
}
class Apartment {
let number: Int
init(number: Int) { self.number = number }
var tenant: Person?
deinit { println("Apartment #(number) is being deinitialized") }
}
Presenter: Waseem Ahmad, Mindfire Solutions
Strong Reference Cycles
Every Person instance has a name property of type String and an optional
apartment property that is initially nil. The apartment property is optional.
var john: Person?
var number73: Apartment?
john = Person(name: "John Appleseed")
number73 = Apartment(number: 73)
john!.apartment = number73
number73!.tenant = john
Unfortunately, linking these two instances creates a strong reference cycle
between them.
Presenter: Waseem Ahmad, Mindfire Solutions
Strong Reference Cycles
Presenter: Waseem Ahmad, Mindfire Solutions
Resolving Strong Reference
Cycles Between Class Instances
Swift provides two ways to resolve strong reference cycles when you work
with properties of class type: weak references and unowned references.
- Week references
- Unowned references
The instances can then refer to each other without creating a strong reference
cycle.
Presenter: Waseem Ahmad, Mindfire Solutions
Weak References
Weak references must be declared as variables, to indicate that their value
can change at runtime. A weak reference cannot be declared as a constant.
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { println("(name) is being deinitialized") }
}
class Apartment {
let number: Int
init(number: Int) { self.number = number }
weak var tenant: Person?
}
Presenter: Waseem Ahmad, Mindfire Solutions
Weak References
Presenter: Waseem Ahmad, Mindfire Solutions
Unowned References
- Does not keep a strong hold on the instance it refers to.
- An unowned reference is assumed to always have a value.
- Because of this, an unowned reference is always defined as a non-optional
type.
Presenter: Waseem Ahmad, Mindfire Solutions
Unowned References
class Customer {
let name: String
var card: CreditCard?
init(name: String) {
self.name = name
}
deinit { println("(name) is being deinitialized") }
}
class CreditCard {
let number: UInt64
unowned let customer: Customer
init(number: UInt64, customer: Customer) {
self.number = number
self.customer = customer
}
deinit { println("Card #(number) is being deinitialized") }
}
Presenter: Waseem Ahmad, Mindfire Solutions
Unowned References
Presenter: Waseem Ahmad, Mindfire Solutions
Unowned/Weak References
Use a weak reference whenever it is valid for that reference to become nil at
some point during its lifetime.
Conversely, use an unowned reference when you know that the reference will
never be nil once it has been set during initialisation.
If you try to access an unowned reference after the instance that it references
is deallocated, you will trigger a runtime error. Use unowned references only
when you are sure that the reference will always refer to an instance.
Note also that Swift guarantees your app will crash if you try to access an
unowned reference after the instance it references is deallocated. You will
never encounter unexpected behaviour in this situation. Your app will always
crash reliably, although you should, of course, prevent it from doing so.
Presenter: Waseem Ahmad, Mindfire Solutions
Extensions
Extensions add new functionality to an existing class, structure, or
enumeration type.
Extensions can add new functionality to a type, but they cannot override
existing functionality.
Extensions in Swift can:
-Add computed properties and computed static properties
-Define instance methods and type methods
-Make an existing type conform to a protocol
Presenter: Waseem Ahmad, Mindfire Solutions
Extension Syntax
extension SomeType {
// new functionality to add to SomeType goes here
}
extension SomeType: SomeProtocol, AnotherProtocol {
// implementation of protocol requirements goes here
}
extension Int {
func repetitions(task: () -> ()) {
for i in 0..<self {
task()
}
}
}
Presenter: Waseem Ahmad, Mindfire Solutions
Our USA client wanted us to develop an iPhone app which would be a
replica of their existing flash-based web-application related to fashion
encompassing all the features of the web-app. User can create account,
register/login, and then play around with the dummy models by creating
makeovers with the available accessories. User even has the facility to
save/upload their makeover as well as vote for other makeovers by
participating in daily/weekly contests. Mindfire responded well to create an
app for this mobile platform that contained 20,000 individual dress-up
elements without loosing quality or speed.
Click to know more >>
CASE STUDY
iPhone Fashion App
www.mindfiresolutions.com
Recap
- Closures
- Structures
- Enum
- Memory Management
- Extensions
Presenter: Waseem Ahmad, Mindfire Solutions
References
- Apple WWDC 2014
- Apple Inc. “The Swift Programming Language.” iBooks.
Presenter: Waseem Ahmad, Mindfire Solutions
Presenter: Waseem Ahmad, Mindfire Solutions
Question and Answer
Thank you
Presenter: Waseem Ahmad, Mindfire Solutions

More Related Content

PPTX
Swift Bengaluru Meetup slides
PPTX
SWIFT 3
PDF
What's new in Swift 3
PPTX
Javascript Basics
PPT
Core java concepts
PDF
JavaScript introduction 1 ( Variables And Values )
PDF
Java Fundamentals
PPTX
JavaScript Basics and Trends
Swift Bengaluru Meetup slides
SWIFT 3
What's new in Swift 3
Javascript Basics
Core java concepts
JavaScript introduction 1 ( Variables And Values )
Java Fundamentals
JavaScript Basics and Trends

What's hot (20)

PDF
Built in classes in java
PDF
Programming in Scala: Notes
ODP
Functional Objects & Function and Closures
PPT
Unit I Advanced Java Programming Course
PDF
PPT
eXo SEA - JavaScript Introduction Training
PDF
Fundamental JavaScript [UTC, March 2014]
PPT
JavaScript Tutorial
PDF
Procedure Typing for Scala
PDF
Swift Programming
PDF
PLSQL CURSOR
PPTX
Hardened JavaScript
PPTX
Scala fundamentals
PDF
Letswift Swift 3.0
PDF
JavaScript 101 - Class 1
PDF
Introduction to Swift
PPTX
PDF
PDF
Connect.Tech- Swift Memory Management
PPT
Java Tut1
Built in classes in java
Programming in Scala: Notes
Functional Objects & Function and Closures
Unit I Advanced Java Programming Course
eXo SEA - JavaScript Introduction Training
Fundamental JavaScript [UTC, March 2014]
JavaScript Tutorial
Procedure Typing for Scala
Swift Programming
PLSQL CURSOR
Hardened JavaScript
Scala fundamentals
Letswift Swift 3.0
JavaScript 101 - Class 1
Introduction to Swift
Connect.Tech- Swift Memory Management
Java Tut1
Ad

Similar to Swift Programming - Part 2 (20)

PPTX
Enumerations, structure and class IN SWIFT
PDF
LEARN C#
PPTX
Full CSE 310 Unit 1 PPT.pptx for java language
PPTX
Hibernate Training Session1
DOC
Class XII Computer Science Study Material
PPT
JavaScript - An Introduction
PPT
Synapseindia dot net development
PPTX
Introduction to Scala
PPT
java
PPT
Java is an Object-Oriented Language
PPT
structures.ppt
PPT
Introduction to structures in c lang.ppt
ODP
(6) c sharp introduction_advanced_features_part_i
ODP
Oop scala
PPTX
CPP Homework Help
DOCX
The Java Learning Kit Chapter 6 – Arrays Copyrigh.docx
PPT
Csharp_mahesh
PDF
Java for android developers
PPTX
Complete Notes on Angular 2 and TypeScript
PPT
Java Script Introduction
Enumerations, structure and class IN SWIFT
LEARN C#
Full CSE 310 Unit 1 PPT.pptx for java language
Hibernate Training Session1
Class XII Computer Science Study Material
JavaScript - An Introduction
Synapseindia dot net development
Introduction to Scala
java
Java is an Object-Oriented Language
structures.ppt
Introduction to structures in c lang.ppt
(6) c sharp introduction_advanced_features_part_i
Oop scala
CPP Homework Help
The Java Learning Kit Chapter 6 – Arrays Copyrigh.docx
Csharp_mahesh
Java for android developers
Complete Notes on Angular 2 and TypeScript
Java Script Introduction
Ad

More from Mindfire Solutions (20)

PDF
Physician Search and Review
PDF
diet management app
PDF
Business Technology Solution
PDF
Remote Health Monitoring
PDF
Influencer Marketing Solution
PPT
High Availability of Azure Applications
PPTX
IOT Hands On
PPTX
Glimpse of Loops Vs Set
ODP
Oracle Sql Developer-Getting Started
PPT
Adaptive Layout In iOS 8
PPT
Introduction to Auto-layout : iOS/Mac
PPT
LINQPad - utility Tool
PPT
Get started with watch kit development
PPTX
Swift vs Objective-C
ODP
Material Design in Android
ODP
Introduction to OData
PPT
Ext js Part 2- MVC
PPT
ExtJs Basic Part-1
PPT
Spring Security Introduction
Physician Search and Review
diet management app
Business Technology Solution
Remote Health Monitoring
Influencer Marketing Solution
High Availability of Azure Applications
IOT Hands On
Glimpse of Loops Vs Set
Oracle Sql Developer-Getting Started
Adaptive Layout In iOS 8
Introduction to Auto-layout : iOS/Mac
LINQPad - utility Tool
Get started with watch kit development
Swift vs Objective-C
Material Design in Android
Introduction to OData
Ext js Part 2- MVC
ExtJs Basic Part-1
Spring Security Introduction

Recently uploaded (20)

PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Digital Strategies for Manufacturing Companies
PPTX
Introduction to Artificial Intelligence
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
history of c programming in notes for students .pptx
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Design an Analysis of Algorithms I-SECS-1021-03
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Odoo Companies in India – Driving Business Transformation.pdf
Digital Strategies for Manufacturing Companies
Introduction to Artificial Intelligence
Which alternative to Crystal Reports is best for small or large businesses.pdf
CHAPTER 2 - PM Management and IT Context
history of c programming in notes for students .pptx
How Creative Agencies Leverage Project Management Software.pdf
VVF-Customer-Presentation2025-Ver1.9.pptx
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Navsoft: AI-Powered Business Solutions & Custom Software Development
Online Work Permit System for Fast Permit Processing
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
How to Choose the Right IT Partner for Your Business in Malaysia
2025 Textile ERP Trends: SAP, Odoo & Oracle
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Internet Downloader Manager (IDM) Crack 6.42 Build 41

Swift Programming - Part 2

  • 1. 1 Swift in depth Presenter: Waseem Ahmad, Mindfire Solutions Date: 18/02/2015
  • 2. What we discussed Presenter: Waseem Ahmad, Mindfire Solutions What is Swift? Variable/Constants String/Character Interpolation Array and Dictionary Loops Optionals, Unwrapping an Optional Functions Tuples Classes Properties
  • 3. What we will Learn Today Presenter: Waseem Ahmad, Mindfire Solutions - Closures - Structures - Enum - Memory Management - Extensions
  • 4. Closures To an Objective-C developer, a closure is Swift’s equivalent of blocks. A formal definition should be that Swift closures are self-contained blocks of functionality that can be passed around and used in your code. Intuitively, a closure is a kind of anonymous, nested functions. It’s a chunk of functionality that can be passed around and used in your code. Presenter: Waseem Ahmad, Mindfire Solutions
  • 5. Swift closures syntax To define one, you’d write something like this: { (parameters) -> return_type in // block body // write code here } {(op1: Double, op2: Double) -> Double in return op1 + op2 } Presenter: Waseem Ahmad, Mindfire Solutions
  • 6. Type Inference {(op1, op2) in return op1 + op2 } Presenter: Waseem Ahmad, Mindfire Solutions Implicit Return {(op1, op2) in op1 + op2}
  • 7. Implicit Arguments performOperation({$0 + $1}) Presenter: Waseem Ahmad, Mindfire Solutions Trailing Closures performOperation() {$0 - $1}
  • 8. Some Closures Definition As a variable: var closureName: (parameterTypes) -> (returnType) As a type alias: typealias closureType = (parameterTypes) -> (returnType) As a function parameter: array.sort({ (item1: Int, item2: Int) -> Bool in return item1 < item2 }) Presenter: Waseem Ahmad, Mindfire Solutions
  • 9. Structure Classes and structures have a similar definition syntax. We introduce classes with the class keyword and structures with the struct keyword. Both place their entire definition within a pair of braces: class SomeClass { // class definition goes here } struct SomeStructure { // structure definition goes here } Presenter: Waseem Ahmad, Mindfire Solutions
  • 10. Structure Declaration struct Point { var x, y: Double } struct Size { var width, height: Double } struct Rect { var origin: Point var size: Size } var point = Point(x: 0.0, y: 0.0) var size = Size(width: 640.0, height: 480.0) var rect = Rect(origin: point, size: size) Presenter: Waseem Ahmad, Mindfire Solutions
  • 11. Swift Structure Swift classes and structures are much closer in functionality than in other languages. - We can define method inside the structure. - We can define property inside the structure. Presenter: Waseem Ahmad, Mindfire Solutions
  • 12. Define properties struct Rect { var origin: Point var size: Size var area: Double { return size.width * size.height } } Presenter: Waseem Ahmad, Mindfire Solutions
  • 13. Define methods struct Rect { var origin: Point var size: Size var area: Double { return size.width * size.height } func isBiggerThanRect(other: Rect) -> Bool { return self.area > other.area } Presenter: Waseem Ahmad, Mindfire Solutions
  • 14. Difference between class and struct - Structures cannot Inherit from other types. - Class Instances are Passed by Reference (Reference Type). “Unlike value types, reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function.” - Structures are Passed by Value (Value Type) “A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function.” - Structures cannot have multiple references to the same instance - Structures do not have deinitializers. Presenter: Waseem Ahmad, Mindfire Solutions
  • 15. Mutating a Structure struct Point { var x, y: Double mutating func moveToTheRightBy(dx: Double) { x += dx } } Presenter: Waseem Ahmad, Mindfire Solutions
  • 16. Enum An enumeration defines a common type for a group of related values. As you are familiar with C, Objective C, you know that C, Objective C enumerations assign related names to a set of integer values. Enumerations in Swift are much more flexible, and do not have to provide a value for each member of the enumeration. the value can be a string, a character, or a value of any integer or floating-point type. Presenter: Waseem Ahmad, Mindfire Solutions
  • 17. Enum Declaration enum CompassPoint { case North case South case East case West } var directionToHead = CompassPoint.West Unlike C and Objective-C, Swift enumeration members are not assigned a default integer value when they are created. In the CompassPoint example above, North, South, East and West do not implicitly equal 0, 1, 2 and 3. Instead, the different enumeration members are fully-fledged values in their own right, with an explicitly-defined type of CompassPoint Presenter: Waseem Ahmad, Mindfire Solutions
  • 18. Enum and row value enum Planet : Int { case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn } let earthsOrder = Planet.Earth.rawValue // earthsOrder is 3 let possiblePlanet = Planet(rawValue: 7) // possiblePlanet is of type Planet? and equals Planet.Uranus enum ASCIIControlCharacter: Character { case Tab = "t" case LineFeed = "n" case CarriageReturn = "r" } Presenter: Waseem Ahmad, Mindfire Solutions
  • 19. Enumerations: Associated Values enum TrainStatus { case OnTime case Delayed(Int) } var status = TrainStatus.OnTime // status is inferred to be a TrainStatus status = .Delayed(42) Presenter: Waseem Ahmad, Mindfire Solutions
  • 20. Enumerations: Properties enum TrainStatus { case OnTime, Delayed(Int) init() { self = OnTime } var description: String { switch self { case OnTime: return "on time" case Delayed(let minutes): return "delayed by (minutes) minute(s)” } } } Presenter: Waseem Ahmad, Mindfire Solutions
  • 21. Enumerations: Properties var status = TrainStatus() println("The train is (status.description)") // The train is on time status = .Delayed(42) println("The train is now (status.description)") // The train is now delayed by 42 minute(s) Presenter: Waseem Ahmad, Mindfire Solutions
  • 22. Memory Management -Swift uses Automatic Reference Counting (ARC) to track and manage your app’s memory usage. -ARC requires information about the relationships between parts of your code in order to manage memory. -Reference counting only applies to instances of classes. Structures and enumerations are value types, not reference types, and are not stored and passed by reference. Presenter: Waseem Ahmad, Mindfire Solutions
  • 23. How ARC Works -Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. Something like book keeping. -Additionally, when an instance is no longer needed, ARC frees up the memory used by that instance. -Reference counting only applies to instances of classes. Structures and enumerations are value types, not reference types, and are not stored and passed by reference. Presenter: Waseem Ahmad, Mindfire Solutions
  • 24. How ARC Works class Person { let name: String init(name: String) { self.name = name } deinit { // prints "John Appleseed is being deinitialized" } } var reference1: Person(name: "John Appleseed") Presenter: Waseem Ahmad, Mindfire Solutions
  • 25. How ARC Works var reference2: Person? var reference3: Person? If you assign the same Person instance to two more variables, two more strong references to that instance are established: reference2 = reference1 reference3 = reference1 There are now three strong references to this single Person instance. Presenter: Waseem Ahmad, Mindfire Solutions
  • 26. How ARC Works reference1 = nil reference2 = nil ARC does not deallocate the Person instance until the third and final strong reference is broken, at which point it is clear that you are no longer using the Person instance: reference3 = nil // prints "John Appleseed is being deinitialized" Presenter: Waseem Ahmad, Mindfire Solutions
  • 27. Strong Reference Cycles In the examples, ARC is able to track the number of references to the new Person instance you create and to deallocate that Person instance when it is no longer needed. However, it is possible to write code in which an instance of a class never gets to a point where it has zero strong references. This can happen if two class instances hold a strong reference to each other, such that each instance keeps the other alive. This is known as a strong reference cycle. Presenter: Waseem Ahmad, Mindfire Solutions
  • 28. Strong Reference Cycles class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { println("(name) is being deinitialized") } } class Apartment { let number: Int init(number: Int) { self.number = number } var tenant: Person? deinit { println("Apartment #(number) is being deinitialized") } } Presenter: Waseem Ahmad, Mindfire Solutions
  • 29. Strong Reference Cycles Every Person instance has a name property of type String and an optional apartment property that is initially nil. The apartment property is optional. var john: Person? var number73: Apartment? john = Person(name: "John Appleseed") number73 = Apartment(number: 73) john!.apartment = number73 number73!.tenant = john Unfortunately, linking these two instances creates a strong reference cycle between them. Presenter: Waseem Ahmad, Mindfire Solutions
  • 30. Strong Reference Cycles Presenter: Waseem Ahmad, Mindfire Solutions
  • 31. Resolving Strong Reference Cycles Between Class Instances Swift provides two ways to resolve strong reference cycles when you work with properties of class type: weak references and unowned references. - Week references - Unowned references The instances can then refer to each other without creating a strong reference cycle. Presenter: Waseem Ahmad, Mindfire Solutions
  • 32. Weak References Weak references must be declared as variables, to indicate that their value can change at runtime. A weak reference cannot be declared as a constant. class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { println("(name) is being deinitialized") } } class Apartment { let number: Int init(number: Int) { self.number = number } weak var tenant: Person? } Presenter: Waseem Ahmad, Mindfire Solutions
  • 33. Weak References Presenter: Waseem Ahmad, Mindfire Solutions
  • 34. Unowned References - Does not keep a strong hold on the instance it refers to. - An unowned reference is assumed to always have a value. - Because of this, an unowned reference is always defined as a non-optional type. Presenter: Waseem Ahmad, Mindfire Solutions
  • 35. Unowned References class Customer { let name: String var card: CreditCard? init(name: String) { self.name = name } deinit { println("(name) is being deinitialized") } } class CreditCard { let number: UInt64 unowned let customer: Customer init(number: UInt64, customer: Customer) { self.number = number self.customer = customer } deinit { println("Card #(number) is being deinitialized") } } Presenter: Waseem Ahmad, Mindfire Solutions
  • 36. Unowned References Presenter: Waseem Ahmad, Mindfire Solutions
  • 37. Unowned/Weak References Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialisation. If you try to access an unowned reference after the instance that it references is deallocated, you will trigger a runtime error. Use unowned references only when you are sure that the reference will always refer to an instance. Note also that Swift guarantees your app will crash if you try to access an unowned reference after the instance it references is deallocated. You will never encounter unexpected behaviour in this situation. Your app will always crash reliably, although you should, of course, prevent it from doing so. Presenter: Waseem Ahmad, Mindfire Solutions
  • 38. Extensions Extensions add new functionality to an existing class, structure, or enumeration type. Extensions can add new functionality to a type, but they cannot override existing functionality. Extensions in Swift can: -Add computed properties and computed static properties -Define instance methods and type methods -Make an existing type conform to a protocol Presenter: Waseem Ahmad, Mindfire Solutions
  • 39. Extension Syntax extension SomeType { // new functionality to add to SomeType goes here } extension SomeType: SomeProtocol, AnotherProtocol { // implementation of protocol requirements goes here } extension Int { func repetitions(task: () -> ()) { for i in 0..<self { task() } } } Presenter: Waseem Ahmad, Mindfire Solutions
  • 40. Our USA client wanted us to develop an iPhone app which would be a replica of their existing flash-based web-application related to fashion encompassing all the features of the web-app. User can create account, register/login, and then play around with the dummy models by creating makeovers with the available accessories. User even has the facility to save/upload their makeover as well as vote for other makeovers by participating in daily/weekly contests. Mindfire responded well to create an app for this mobile platform that contained 20,000 individual dress-up elements without loosing quality or speed. Click to know more >> CASE STUDY iPhone Fashion App www.mindfiresolutions.com
  • 41. Recap - Closures - Structures - Enum - Memory Management - Extensions Presenter: Waseem Ahmad, Mindfire Solutions
  • 42. References - Apple WWDC 2014 - Apple Inc. “The Swift Programming Language.” iBooks. Presenter: Waseem Ahmad, Mindfire Solutions
  • 43. Presenter: Waseem Ahmad, Mindfire Solutions Question and Answer
  • 44. Thank you Presenter: Waseem Ahmad, Mindfire Solutions