SlideShare a Scribd company logo
Deep Dive Into
Swift
@sarat
Software Architect
A bit of history
Chris Lattner
• Author of the original
LLVM tool chain project
• Started working on Swift
in 2010
• A research intern at
Microsoft Research
• Leads Development Tool
Effort at Apple
Why Swift?
Modern Compilers and
Optimization
Techniques
Influenced by Python,
Ruby, Objective-C, C#
etc.
Productivity
+
Native Performance
easy to learn
Playground & REPL
Playground
REPL (Read-Eval-Print-Loop)
- Write it in lldb when program runs
- Use xcrun swift to run externally
Transparent
interaction with
Objective-C & C
can deploy to previous
version of iOS and OS X
wide adoption in
short time
– The RedMonk Programming Language Rankings: January 2015
“Swift has gone from our 68th ranked
language during Q3 to number 22 this
quarter, a jump of 46 spots.”
Why Swift Performs
better?
Smaller Runtime
generates native
code
Swift Compiler
Architecture
Deep Dive Into Swift
Deep Dive Into Swift
Enumerations
similar to other
languages
enum CompassPoint {
case North
case South
case East
case West
}
enum CompassPoint {
case North
case South
case East
case West
}
var directionToHead = CompassPoint.East;
directionToHead = .East;
enum CompassPoint {
case North
case South
case East
case West
}
var directionToHead = CompassPoint.East;
directionToHead = .East;
switch(directionToHead) {
case .East:
println( "Heading east")
case .West:
println( "Heading West")
case .North:
println( "Heading North")
case .South:
println( "Heading South")
default:
println("Nowhere to go")
}
associated values
Enumerations can store associated
values of any given type.
The type can be different for each
member in the enumeration
// Associated Values Examples
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
// Associated Values Examples
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
productBarcode = .QRCode("ABCDEFGHIJ")
// Associated Values Examples
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
productBarcode = .QRCode("ABCDEFGHIJ")
let numberSystem = 8, manufacturer = 85909,
product = 51226, check = 3
switch productBarcode {
case let .UPCA(numberSystem, manufacturer, product, check)
println("UPCA Detected")
case let .QRCode("ABCDEFGHIJ")
println("QRCode detected")
}
switch-case pattern
matching
// Pattern Matching with Switch-Case
let x = 9
switch(x) {
case 1...5: // Closed range operator
println( "Range - 1,2,3,4,5")
case 6..<10: // Half closed range operator
println( "Range - 6,7,8,9")
default:
println("Default")
}
Properties
associates values with
classes, structure or
enumerations
Stored Properties
store constant and
variable values
Lazy Stored Properties
• Initializes on first time access
• Declared with lazy keyword
• Lazy Stored properties can’t be a constant;
for obvious reasons
• Useful when the initial values are depends
on outside factors
// Lazy initialization
class DataImporter {
}
class DataManager {
lazy var importer = DataImporter()
var data = [String]()
}
let m = DataManager()
// importer has not yet been created
m.data.append("Element 1");
m.data.append("Element 2");
m.data.append("Element 3");
// Initialize on first access
m.importer.import();
Computed Properties
computes a value
(rather than store)
// Computed properties
class Rectangle {
var height = 0
var width = 0
var area : Int {
get {
return height * width
}
}
}
Property Observers
// Property Observers
class Temperature {
var current : Int = 26 {
willSet {
println("(newValue)");
// Prints 32
}
didSet {
println("(oldValue)");
// Prints 26
}
}
}
var obj = Temperature()
obj.current = 32;
Override properties
Closures
Self-contained blocks of
functionality that can be
passed around and used in
your code.
Similar to blocks in
Objective-C
Closures
// Closures
var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"]
// Sort with delegates
cities.sort({ (a, b) -> Bool in
a < b
})
Closures - Trailing spaces
// Closures
var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"]
// Sort with delegates
cities.sort({ (a, b) -> Bool in
a < b
})
Closures - Parentheses
// Closures
var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"]
// Sort with delegates
cities.sort { (a, b) -> Bool in
a < b
}
Closures - Type inference
// Closures
var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"]
// Sort with delegates
cities.sort { (a, b) -> Bool in
a < b
}
Closures - Type inference
// Closures
var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"]
// Sort with delegates
cities.sort { a, b -> Bool in
a < b
}
Closures - Implicit return
// Closures
var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"]
// Sort with delegates
cities.sort { a, b in
a < b
}
Closures - Positional
Parameters
// Closures
var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"]
// Sort with delegates — Positional parameters
cities.sort { $0 < $1 }
Closures - Operator as
closure
// Closures
var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"]
// Sounds interesting?
cities.sort( < )
Optionals
represent possible
missing values
stack.pop?
response.parse().age?
// Age can be nil
var age : Int?
age = response.parse()
Unwrapping
var age : Int?
age = response.parse()
let x = age!
// Your program would crash if you unwrap a nil value
Optional Binding
class Person {
var residence : Residence?
}
class Residence {
var address : Address?
}
class Address {
var buildingNumber : String?
var streetName : String?
var apartmentNumber : String?
}
// Optional Binding
if let home = paul.residence {
if let postalAddress = home.address {
if let building = postalAddress.buildingNumber {
// Code
}
}
}
Optional Chaining
// Optional Chaining
let buildingNumber = paul.residence?.address?.buildingNumber
// optional chaining + bind + unwrap
if let buildingNumber = paul.residence?.address?.buildingNumber {
}
Initializer
Convenience &
Designated Initializers
designated initializers are primary
initializers of a class
a class must have at least one
designated initializer
classes tend to have few
designated initializers
convenience initializers
are secondary; supporting
initializers of a class
class Food {
var name: String
// Designated Initializer
init(name: String) {
self.name = name
}
// Convenience Initializer
convenience init() {
self.init(name: "Unnamed")
}
}
class Food {
var name: String
// Designated Initializer
init(name: String) {
self.name = name
}
// Convenience Initializer
convenience init() {
self.init(name: "Unnamed")
}
}
class Food {
var name: String
// Designated Initializer
init(name: String) {
self.name = name
}
// Convenience Initializer
convenience init() {
self.init(name: "Unnamed")
}
}
overriding
initializers
class Vehicle {
let numberOfWheels = 0
}
class Bicycle : Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
class Car : Vehicle {
override init() {
super.init()
numberOfWheels = 4
}
}
class Vehicle {
let numberOfWheels = 0
}
class Bicycle : Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
class Car : Vehicle {
override init() {
super.init()
numberOfWheels = 4
}
}
class Vehicle {
let numberOfWheels = 0
}
class Bicycle : Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
class Car : Vehicle {
override init() {
super.init()
numberOfWheels = 4
}
}
class Vehicle {
let numberOfWheels = 0
}
class Bicycle : Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
class Car : Vehicle {
override init() {
super.init()
numberOfWheels = 4
}
}
Extensions
helps you to attach
functionality data types; even
to the ones you didn’t create!
// Extension as instance method
extension Int {
func plusOne() -> Int {
return self + 1
}
}
var i = 5
i.plusOne()
10.plusOne()
// Extension as instance method
extension Int {
func plusOne() -> Int {
return self + 1
}
}
var i = 5
i.plusOne()
10.plusOne()
// Extension as instance method
extension Int {
func plusOne() -> Int {
return self + 1
}
}
var i = 5
i.plusOne()
10.plusOne()
// Extension as property
extension Double {
var km : Double { return self*1000.0 }
var m : Double { return self }
var cm : Double { return self / 100.0 }
var mm : Double { return self / 10000.0 }
var ft : Double { return self / 3.28084 }
}
let threeFeet = 3.ft // Meters
let oneInch = 25.4.mm // Meters
// Extension as property
extension Double {
var km : Double { return self*1000.0 }
var m : Double { return self }
var cm : Double { return self / 100.0 }
var mm : Double { return self / 10000.0 }
var ft : Double { return self / 3.28084 }
}
let threeFeet = 3.ft // Meters
let oneInch = 25.4.mm // Meters
// Extension as property
extension Double {
var km : Double { return self*1000.0 }
var m : Double { return self }
var cm : Double { return self / 100.0 }
var mm : Double { return self / 10000.0 }
var ft : Double { return self / 3.28084 }
}
let threeFeet = 3.ft // Meters
let oneInch = 25.4.mm // Meters
// Extension as class method
extension UIColor {
class func chilliRed() -> UIColor {
return UIColor(red: 94/255, green: 25/255, blue: 33/255,
alpha: 1)
}
}
var chilliRed = UIColor.chilliRed()
// Extension as class method
extension UIColor {
class func chilliRed() -> UIColor {
return UIColor(red: 94/255, green: 25/255, blue: 33/255,
alpha: 1)
}
}
var chilliRed = UIColor.chilliRed()
// Extension as class method
extension UIColor {
class func chilliRed() -> UIColor {
return UIColor(red: 94/255, green: 25/255, blue: 33/255,
alpha: 1)
}
}
var chilliRed = UIColor.chilliRed()
Protocols &
Delegates
Protocols are
interface definitions
class ViewController: UIViewController, FBLoginViewDelegate {
}
class ViewController: UIViewController, FBLoginViewDelegate {
}
Class
class ViewController: UIViewController, FBLoginViewDelegate {
}
ProtocolClass
protocol LoginProtocol {
func loginSuccessful()
func loginFailed()
}
class ViewController : LoginProtocol {
func loginFailed() {
// code
}
func loginSuccessful() {
// code
}
}
protocol LoginProtocol {
var someProperty : Int { get set }
func loginSuccessful()
func loginFailed()
}
class ViewController : LoginProtocol {
func loginFailed() {
// code
}
func loginSuccessful() {
// code
}
var someProperty : Int = 0 {
willSet {
// Update UI with newValue
}
didSet {
// code
}
}
}
protocol LoginProtocol {
var someProperty : Int { get set }
func loginSuccessful()
func loginFailed()
}
class ViewController : LoginProtocol {
func loginFailed() {
// code
}
func loginSuccessful() {
// code
}
var someProperty : Int = 0 {
willSet {
// Update UI with newValue
}
didSet {
// code
}
}
}
protocol LoginProtocol {
var someProperty : Int { get set }
func loginSuccessful()
func loginFailed()
}
class ViewController : LoginProtocol {
func loginFailed() {
// code
}
func loginSuccessful() {
// code
}
var someProperty : Int = 0 {
willSet {
// Update UI with newValue
}
didSet {
// code
}
}
}
protocol LoginProtocol {
var someProperty : Int { get set }
func loginSuccessful()
func loginFailed()
}
class ViewController : LoginProtocol {
func loginFailed() {
// code
}
func loginSuccessful() {
// code
}
var someProperty : Int = 0 {
willSet {
// Update UI with newValue
}
didSet {
// code
}
}
}
Generics
func swapInt(inout a:Int, inout b:Int) {
let t = a; a = b; b = t
}
func swapString(inout a:String, inout b:String) {
let t = a; a = b; b = t
}
var a = 10, b = 20
swapInt(&a, &b)
var p = "iOS 7", q = "iOS 8"
swapString(&p,&q)
func swapInt(inout a:Int, inout b:Int) {
let t = a; a = b; b = t
}
func swapString(inout a:String, inout b:String) {
let t = a; a = b; b = t
}
var a = 10, b = 20
swapInt(&a, &b)
var p = "iOS 7", q = "iOS 8"
swapString(&p,&q)
// MARK: With Generics
func Swap <T> (inout a: T, inout b: T) {
let t = a; a = b; b = t
}
Swap(&a, &b);
Swap(&p, &q);
func swapInt(inout a:Int, inout b:Int) {
let t = a; a = b; b = t
}
func swapString(inout a:String, inout b:String) {
let t = a; a = b; b = t
}
var a = 10, b = 20
swapInt(&a, &b)
var p = "iOS 7", q = "iOS 8"
swapString(&p,&q)
// MARK: With Generics
func Swap <T> (inout a: T, inout b: T) {
let t = a; a = b; b = t
}
Swap(&a, &b);
Swap(&p, &q);
// Generic Type
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
// Stack from somewhere
class Stack<T> {
}
// Extension
extension Stack {
func top() -> T? {
return nil
}
}
// Type constraints
func findIndex<T: Equatable>( array: [T], valueToFind: T) -> Int? {
for(index, value) in enumerate(array) {
if value == valueToFind {
return index
}
}
return nil
}
Mutating
Structures and enumerations are value
types.
By default, the properties of a value type
cannot be modified from within its
instance methods.
// Immutatbility and Mutating
struct Point {
var x = 0.0, y = 0.0
// No change in the actual object
func pointByScaling(factor: Double) -> Point {
return Point(x: self.x*factor, y: self.y*factor)
}
// Function modifies the object
mutating func scale(factor : Double) {
self.x *= factor
self.y *= factor
}
}
// Immutatbility and Mutating
struct Point {
var x = 0.0, y = 0.0
// No change in the actual object
func pointByScaling(factor: Double) -> Point {
return Point(x: self.x*factor, y: self.y*factor)
}
// Function modifies the object
mutating func scale(factor : Double) {
self.x *= factor
self.y *= factor
}
}
// Immutatbility and Mutating
struct Point {
var x = 0.0, y = 0.0
// No change in the actual object
func pointByScaling(factor: Double) -> Point {
return Point(x: self.x*factor, y: self.y*factor)
}
// Function modifies the object
mutating func scale(factor : Double) {
self.x *= factor
self.y *= factor
}
}
Advanced
Operators
struct Vector2D {
var x = 0.0, y = 0.0
}
func + (left:Vector2D, right:Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
// Compound Operator
func += (inout left:Vector2D, right:Vector2D) {
left.x += right.x
left.y += right.y
}
var vector = Vector2D(x: 3.0, y: 1.0)
let anotherVector = Vector2D(x: 2.0, y: 4.0)
let combinedVector = vector + anotherVector
vector += anotherVector
struct Vector2D {
var x = 0.0, y = 0.0
}
func + (left:Vector2D, right:Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
// Compound Operator
func += (inout left:Vector2D, right:Vector2D) {
left.x += right.x
left.y += right.y
}
var vector = Vector2D(x: 3.0, y: 1.0)
let anotherVector = Vector2D(x: 2.0, y: 4.0)
let combinedVector = vector + anotherVector
vector += anotherVector
struct Vector2D {
var x = 0.0, y = 0.0
}
func + (left:Vector2D, right:Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
// Compound Operator
func += (inout left:Vector2D, right:Vector2D) {
left.x += right.x
left.y += right.y
}
var vector = Vector2D(x: 3.0, y: 1.0)
let anotherVector = Vector2D(x: 2.0, y: 4.0)
let combinedVector = vector + anotherVector
vector += anotherVector
struct Vector2D {
var x = 0.0, y = 0.0
}
func + (left:Vector2D, right:Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
// Compound Operator
func += (inout left:Vector2D, right:Vector2D) {
left.x += right.x
left.y += right.y
}
var vector = Vector2D(x: 3.0, y: 1.0)
let anotherVector = Vector2D(x: 2.0, y: 4.0)
let combinedVector = vector + anotherVector
vector += anotherVector
struct Vector2D {
var x = 0.0, y = 0.0
}
// Custom operator - Doubling
prefix operator +++ {}
prefix func +++ (inout vector: Vector2D) ->
Vector2D {
vector += vector
return vector
}
let doubled = +++vector
struct Vector2D {
var x = 0.0, y = 0.0
}
// Custom operator - Doubling
prefix operator +++ {}
prefix func +++ (inout vector: Vector2D) ->
Vector2D {
vector += vector
return vector
}
let doubled = +++vector
struct Vector2D {
var x = 0.0, y = 0.0
}
// Custom operator - Doubling
prefix operator +++ {}
prefix func +++ (inout vector: Vector2D) ->
Vector2D {
vector += vector
return vector
}
let doubled = +++vector
operators are only
allowed in global
scope
Using Objective-C
frameworks with Swift
Bridging Header
Deep Dive Into Swift
Demo - FacebookSDK
Integration
References
• The Swift Programming Language - iBooks
• Using Swift with Objective-C and Cocoa -
iBooks
• WWDC 2014 Sessions on Swift
• Developing iOS 8 Apps with Swift -
iTunesU - Stanford

More Related Content

PDF
Swift Programming Language
PDF
Programming Language Swift Overview
PDF
Swift Programming Language
PDF
Introduction to Swift programming language.
KEY
Evolving Tests
PPTX
Functional Programming in JavaScript by Luis Atencio
PDF
PHP Performance Trivia
PDF
Quick swift tour
Swift Programming Language
Programming Language Swift Overview
Swift Programming Language
Introduction to Swift programming language.
Evolving Tests
Functional Programming in JavaScript by Luis Atencio
PHP Performance Trivia
Quick swift tour

What's hot (20)

PDF
Working with Cocoa and Objective-C
PDF
Cocoa Design Patterns in Swift
PDF
Opaque Pointers Are Coming
PDF
Typed Properties and more: What's coming in PHP 7.4?
PDF
Denis Lebedev, Swift
PDF
Swift in SwiftUI
ODP
Learn JavaScript by modeling Rubik Cube
PDF
Symfony World - Symfony components and design patterns
PDF
Being functional in PHP (DPC 2016)
PDF
Swift Introduction
PDF
Intro to Functional Programming
PDF
Learning Functional Programming Without Growing a Neckbeard
PDF
A swift introduction to Swift
PDF
Dutch php a short tale about state machine
PDF
C++ L10-Inheritance
PDF
Nikita Popov "What’s new in PHP 8.0?"
PDF
Ankara Jug - Practical Functional Programming with Scala
PDF
Twig tips and tricks
PPTX
Things about Functional JavaScript
PDF
One Monad to Rule Them All
Working with Cocoa and Objective-C
Cocoa Design Patterns in Swift
Opaque Pointers Are Coming
Typed Properties and more: What's coming in PHP 7.4?
Denis Lebedev, Swift
Swift in SwiftUI
Learn JavaScript by modeling Rubik Cube
Symfony World - Symfony components and design patterns
Being functional in PHP (DPC 2016)
Swift Introduction
Intro to Functional Programming
Learning Functional Programming Without Growing a Neckbeard
A swift introduction to Swift
Dutch php a short tale about state machine
C++ L10-Inheritance
Nikita Popov "What’s new in PHP 8.0?"
Ankara Jug - Practical Functional Programming with Scala
Twig tips and tricks
Things about Functional JavaScript
One Monad to Rule Them All
Ad

Viewers also liked (9)

PPTX
Swift UI in CloudStack
PPTX
iOS development using Swift - Swift Basics (2)
PDF
iOS Automation Frameworks evaluation
PDF
Fastlane - Automation and Continuous Delivery for iOS Apps
PDF
The Swift Programming Language with iOS App
PPTX
Swift LA Meetup at eHarmony - What You Might Have Missed at WWDC 2015 with Ch...
PDF
tvOS, The Focus Engine, and Swift
PDF
iOS 8/Swift 概要 #ios8yahoo
PDF
Swift Introduction
Swift UI in CloudStack
iOS development using Swift - Swift Basics (2)
iOS Automation Frameworks evaluation
Fastlane - Automation and Continuous Delivery for iOS Apps
The Swift Programming Language with iOS App
Swift LA Meetup at eHarmony - What You Might Have Missed at WWDC 2015 with Ch...
tvOS, The Focus Engine, and Swift
iOS 8/Swift 概要 #ios8yahoo
Swift Introduction
Ad

Similar to Deep Dive Into Swift (20)

PDF
Lecture 5
PDF
All Aboard The Scala-to-PureScript Express!
PDF
Unit3_OOP-converted.pdf
PPT
Csharp4 objects and_types
PDF
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
PDF
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
PDF
The Swift Compiler and Standard Library
PPTX
TypeScript Presentation - Jason Haffey
PDF
Minimizing Decision Fatigue to Improve Team Productivity
ZIP
PPT
Effecient javascript
PDF
Object Oriented Programming (OOP) using C++ - Lecture 1
PDF
Classes
PPT
A First Date With Scala
PDF
Infinum iOS Talks #1 - Swift done right by Ivan Dikic
PDF
TypeScript for Java Developers
PDF
Functions And Header Files In C++ | Bjarne stroustrup
PPTX
Scala fundamentals
PPTX
Lambdas puzzler - Peter Lawrey
PDF
Doctrine For Beginners
Lecture 5
All Aboard The Scala-to-PureScript Express!
Unit3_OOP-converted.pdf
Csharp4 objects and_types
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
The Swift Compiler and Standard Library
TypeScript Presentation - Jason Haffey
Minimizing Decision Fatigue to Improve Team Productivity
Effecient javascript
Object Oriented Programming (OOP) using C++ - Lecture 1
Classes
A First Date With Scala
Infinum iOS Talks #1 - Swift done right by Ivan Dikic
TypeScript for Java Developers
Functions And Header Files In C++ | Bjarne stroustrup
Scala fundamentals
Lambdas puzzler - Peter Lawrey
Doctrine For Beginners

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
A Presentation on Artificial Intelligence
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Empathic Computing: Creating Shared Understanding
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Network Security Unit 5.pdf for BCA BBA.
The AUB Centre for AI in Media Proposal.docx
Reach Out and Touch Someone: Haptics and Empathic Computing
Encapsulation_ Review paper, used for researhc scholars
Digital-Transformation-Roadmap-for-Companies.pptx
A Presentation on Artificial Intelligence
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
NewMind AI Weekly Chronicles - August'25 Week I
Understanding_Digital_Forensics_Presentation.pptx
cuic standard and advanced reporting.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Empathic Computing: Creating Shared Understanding
Unlocking AI with Model Context Protocol (MCP)
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Dropbox Q2 2025 Financial Results & Investor Presentation
Network Security Unit 5.pdf for BCA BBA.

Deep Dive Into Swift

  • 3. A bit of history
  • 4. Chris Lattner • Author of the original LLVM tool chain project • Started working on Swift in 2010 • A research intern at Microsoft Research • Leads Development Tool Effort at Apple
  • 7. Influenced by Python, Ruby, Objective-C, C# etc.
  • 12. REPL (Read-Eval-Print-Loop) - Write it in lldb when program runs - Use xcrun swift to run externally
  • 14. can deploy to previous version of iOS and OS X
  • 16. – The RedMonk Programming Language Rankings: January 2015 “Swift has gone from our 68th ranked language during Q3 to number 22 this quarter, a jump of 46 spots.”
  • 25. enum CompassPoint { case North case South case East case West }
  • 26. enum CompassPoint { case North case South case East case West } var directionToHead = CompassPoint.East; directionToHead = .East;
  • 27. enum CompassPoint { case North case South case East case West } var directionToHead = CompassPoint.East; directionToHead = .East; switch(directionToHead) { case .East: println( "Heading east") case .West: println( "Heading West") case .North: println( "Heading North") case .South: println( "Heading South") default: println("Nowhere to go") }
  • 29. Enumerations can store associated values of any given type. The type can be different for each member in the enumeration
  • 30. // Associated Values Examples enum Barcode { case UPCA(Int, Int, Int, Int) case QRCode(String) }
  • 31. // Associated Values Examples enum Barcode { case UPCA(Int, Int, Int, Int) case QRCode(String) } var productBarcode = Barcode.UPCA(8, 85909, 51226, 3) productBarcode = .QRCode("ABCDEFGHIJ")
  • 32. // Associated Values Examples enum Barcode { case UPCA(Int, Int, Int, Int) case QRCode(String) } var productBarcode = Barcode.UPCA(8, 85909, 51226, 3) productBarcode = .QRCode("ABCDEFGHIJ") let numberSystem = 8, manufacturer = 85909, product = 51226, check = 3 switch productBarcode { case let .UPCA(numberSystem, manufacturer, product, check) println("UPCA Detected") case let .QRCode("ABCDEFGHIJ") println("QRCode detected") }
  • 34. // Pattern Matching with Switch-Case let x = 9 switch(x) { case 1...5: // Closed range operator println( "Range - 1,2,3,4,5") case 6..<10: // Half closed range operator println( "Range - 6,7,8,9") default: println("Default") }
  • 36. associates values with classes, structure or enumerations
  • 37. Stored Properties store constant and variable values
  • 38. Lazy Stored Properties • Initializes on first time access • Declared with lazy keyword • Lazy Stored properties can’t be a constant; for obvious reasons • Useful when the initial values are depends on outside factors
  • 39. // Lazy initialization class DataImporter { } class DataManager { lazy var importer = DataImporter() var data = [String]() } let m = DataManager() // importer has not yet been created m.data.append("Element 1"); m.data.append("Element 2"); m.data.append("Element 3"); // Initialize on first access m.importer.import();
  • 40. Computed Properties computes a value (rather than store)
  • 41. // Computed properties class Rectangle { var height = 0 var width = 0 var area : Int { get { return height * width } } }
  • 43. // Property Observers class Temperature { var current : Int = 26 { willSet { println("(newValue)"); // Prints 32 } didSet { println("(oldValue)"); // Prints 26 } } } var obj = Temperature() obj.current = 32;
  • 46. Self-contained blocks of functionality that can be passed around and used in your code.
  • 47. Similar to blocks in Objective-C
  • 48. Closures // Closures var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort({ (a, b) -> Bool in a < b })
  • 49. Closures - Trailing spaces // Closures var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort({ (a, b) -> Bool in a < b })
  • 50. Closures - Parentheses // Closures var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort { (a, b) -> Bool in a < b }
  • 51. Closures - Type inference // Closures var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort { (a, b) -> Bool in a < b }
  • 52. Closures - Type inference // Closures var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort { a, b -> Bool in a < b }
  • 53. Closures - Implicit return // Closures var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates cities.sort { a, b in a < b }
  • 54. Closures - Positional Parameters // Closures var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sort with delegates — Positional parameters cities.sort { $0 < $1 }
  • 55. Closures - Operator as closure // Closures var cities = ["New Delhi", "Trivandrum", "Kochi", "Bangalore"] // Sounds interesting? cities.sort( < )
  • 59. // Age can be nil var age : Int? age = response.parse()
  • 61. var age : Int? age = response.parse() let x = age! // Your program would crash if you unwrap a nil value
  • 63. class Person { var residence : Residence? } class Residence { var address : Address? } class Address { var buildingNumber : String? var streetName : String? var apartmentNumber : String? }
  • 64. // Optional Binding if let home = paul.residence { if let postalAddress = home.address { if let building = postalAddress.buildingNumber { // Code } } }
  • 66. // Optional Chaining let buildingNumber = paul.residence?.address?.buildingNumber
  • 67. // optional chaining + bind + unwrap if let buildingNumber = paul.residence?.address?.buildingNumber { }
  • 70. designated initializers are primary initializers of a class a class must have at least one designated initializer classes tend to have few designated initializers
  • 71. convenience initializers are secondary; supporting initializers of a class
  • 72. class Food { var name: String // Designated Initializer init(name: String) { self.name = name } // Convenience Initializer convenience init() { self.init(name: "Unnamed") } }
  • 73. class Food { var name: String // Designated Initializer init(name: String) { self.name = name } // Convenience Initializer convenience init() { self.init(name: "Unnamed") } }
  • 74. class Food { var name: String // Designated Initializer init(name: String) { self.name = name } // Convenience Initializer convenience init() { self.init(name: "Unnamed") } }
  • 76. class Vehicle { let numberOfWheels = 0 } class Bicycle : Vehicle { override init() { super.init() numberOfWheels = 2 } } class Car : Vehicle { override init() { super.init() numberOfWheels = 4 } }
  • 77. class Vehicle { let numberOfWheels = 0 } class Bicycle : Vehicle { override init() { super.init() numberOfWheels = 2 } } class Car : Vehicle { override init() { super.init() numberOfWheels = 4 } }
  • 78. class Vehicle { let numberOfWheels = 0 } class Bicycle : Vehicle { override init() { super.init() numberOfWheels = 2 } } class Car : Vehicle { override init() { super.init() numberOfWheels = 4 } }
  • 79. class Vehicle { let numberOfWheels = 0 } class Bicycle : Vehicle { override init() { super.init() numberOfWheels = 2 } } class Car : Vehicle { override init() { super.init() numberOfWheels = 4 } }
  • 81. helps you to attach functionality data types; even to the ones you didn’t create!
  • 82. // Extension as instance method extension Int { func plusOne() -> Int { return self + 1 } } var i = 5 i.plusOne() 10.plusOne()
  • 83. // Extension as instance method extension Int { func plusOne() -> Int { return self + 1 } } var i = 5 i.plusOne() 10.plusOne()
  • 84. // Extension as instance method extension Int { func plusOne() -> Int { return self + 1 } } var i = 5 i.plusOne() 10.plusOne()
  • 85. // Extension as property extension Double { var km : Double { return self*1000.0 } var m : Double { return self } var cm : Double { return self / 100.0 } var mm : Double { return self / 10000.0 } var ft : Double { return self / 3.28084 } } let threeFeet = 3.ft // Meters let oneInch = 25.4.mm // Meters
  • 86. // Extension as property extension Double { var km : Double { return self*1000.0 } var m : Double { return self } var cm : Double { return self / 100.0 } var mm : Double { return self / 10000.0 } var ft : Double { return self / 3.28084 } } let threeFeet = 3.ft // Meters let oneInch = 25.4.mm // Meters
  • 87. // Extension as property extension Double { var km : Double { return self*1000.0 } var m : Double { return self } var cm : Double { return self / 100.0 } var mm : Double { return self / 10000.0 } var ft : Double { return self / 3.28084 } } let threeFeet = 3.ft // Meters let oneInch = 25.4.mm // Meters
  • 88. // Extension as class method extension UIColor { class func chilliRed() -> UIColor { return UIColor(red: 94/255, green: 25/255, blue: 33/255, alpha: 1) } } var chilliRed = UIColor.chilliRed()
  • 89. // Extension as class method extension UIColor { class func chilliRed() -> UIColor { return UIColor(red: 94/255, green: 25/255, blue: 33/255, alpha: 1) } } var chilliRed = UIColor.chilliRed()
  • 90. // Extension as class method extension UIColor { class func chilliRed() -> UIColor { return UIColor(red: 94/255, green: 25/255, blue: 33/255, alpha: 1) } } var chilliRed = UIColor.chilliRed()
  • 93. class ViewController: UIViewController, FBLoginViewDelegate { }
  • 94. class ViewController: UIViewController, FBLoginViewDelegate { } Class
  • 95. class ViewController: UIViewController, FBLoginViewDelegate { } ProtocolClass
  • 96. protocol LoginProtocol { func loginSuccessful() func loginFailed() } class ViewController : LoginProtocol { func loginFailed() { // code } func loginSuccessful() { // code } }
  • 97. protocol LoginProtocol { var someProperty : Int { get set } func loginSuccessful() func loginFailed() } class ViewController : LoginProtocol { func loginFailed() { // code } func loginSuccessful() { // code } var someProperty : Int = 0 { willSet { // Update UI with newValue } didSet { // code } } }
  • 98. protocol LoginProtocol { var someProperty : Int { get set } func loginSuccessful() func loginFailed() } class ViewController : LoginProtocol { func loginFailed() { // code } func loginSuccessful() { // code } var someProperty : Int = 0 { willSet { // Update UI with newValue } didSet { // code } } }
  • 99. protocol LoginProtocol { var someProperty : Int { get set } func loginSuccessful() func loginFailed() } class ViewController : LoginProtocol { func loginFailed() { // code } func loginSuccessful() { // code } var someProperty : Int = 0 { willSet { // Update UI with newValue } didSet { // code } } }
  • 100. protocol LoginProtocol { var someProperty : Int { get set } func loginSuccessful() func loginFailed() } class ViewController : LoginProtocol { func loginFailed() { // code } func loginSuccessful() { // code } var someProperty : Int = 0 { willSet { // Update UI with newValue } didSet { // code } } }
  • 102. func swapInt(inout a:Int, inout b:Int) { let t = a; a = b; b = t } func swapString(inout a:String, inout b:String) { let t = a; a = b; b = t } var a = 10, b = 20 swapInt(&a, &b) var p = "iOS 7", q = "iOS 8" swapString(&p,&q)
  • 103. func swapInt(inout a:Int, inout b:Int) { let t = a; a = b; b = t } func swapString(inout a:String, inout b:String) { let t = a; a = b; b = t } var a = 10, b = 20 swapInt(&a, &b) var p = "iOS 7", q = "iOS 8" swapString(&p,&q) // MARK: With Generics func Swap <T> (inout a: T, inout b: T) { let t = a; a = b; b = t } Swap(&a, &b); Swap(&p, &q);
  • 104. func swapInt(inout a:Int, inout b:Int) { let t = a; a = b; b = t } func swapString(inout a:String, inout b:String) { let t = a; a = b; b = t } var a = 10, b = 20 swapInt(&a, &b) var p = "iOS 7", q = "iOS 8" swapString(&p,&q) // MARK: With Generics func Swap <T> (inout a: T, inout b: T) { let t = a; a = b; b = t } Swap(&a, &b); Swap(&p, &q);
  • 105. // Generic Type struct Stack<T> { var items = [T]() mutating func push(item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } }
  • 106. // Stack from somewhere class Stack<T> { } // Extension extension Stack { func top() -> T? { return nil } }
  • 107. // Type constraints func findIndex<T: Equatable>( array: [T], valueToFind: T) -> Int? { for(index, value) in enumerate(array) { if value == valueToFind { return index } } return nil }
  • 109. Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.
  • 110. // Immutatbility and Mutating struct Point { var x = 0.0, y = 0.0 // No change in the actual object func pointByScaling(factor: Double) -> Point { return Point(x: self.x*factor, y: self.y*factor) } // Function modifies the object mutating func scale(factor : Double) { self.x *= factor self.y *= factor } }
  • 111. // Immutatbility and Mutating struct Point { var x = 0.0, y = 0.0 // No change in the actual object func pointByScaling(factor: Double) -> Point { return Point(x: self.x*factor, y: self.y*factor) } // Function modifies the object mutating func scale(factor : Double) { self.x *= factor self.y *= factor } }
  • 112. // Immutatbility and Mutating struct Point { var x = 0.0, y = 0.0 // No change in the actual object func pointByScaling(factor: Double) -> Point { return Point(x: self.x*factor, y: self.y*factor) } // Function modifies the object mutating func scale(factor : Double) { self.x *= factor self.y *= factor } }
  • 114. struct Vector2D { var x = 0.0, y = 0.0 } func + (left:Vector2D, right:Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } // Compound Operator func += (inout left:Vector2D, right:Vector2D) { left.x += right.x left.y += right.y } var vector = Vector2D(x: 3.0, y: 1.0) let anotherVector = Vector2D(x: 2.0, y: 4.0) let combinedVector = vector + anotherVector vector += anotherVector
  • 115. struct Vector2D { var x = 0.0, y = 0.0 } func + (left:Vector2D, right:Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } // Compound Operator func += (inout left:Vector2D, right:Vector2D) { left.x += right.x left.y += right.y } var vector = Vector2D(x: 3.0, y: 1.0) let anotherVector = Vector2D(x: 2.0, y: 4.0) let combinedVector = vector + anotherVector vector += anotherVector
  • 116. struct Vector2D { var x = 0.0, y = 0.0 } func + (left:Vector2D, right:Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } // Compound Operator func += (inout left:Vector2D, right:Vector2D) { left.x += right.x left.y += right.y } var vector = Vector2D(x: 3.0, y: 1.0) let anotherVector = Vector2D(x: 2.0, y: 4.0) let combinedVector = vector + anotherVector vector += anotherVector
  • 117. struct Vector2D { var x = 0.0, y = 0.0 } func + (left:Vector2D, right:Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } // Compound Operator func += (inout left:Vector2D, right:Vector2D) { left.x += right.x left.y += right.y } var vector = Vector2D(x: 3.0, y: 1.0) let anotherVector = Vector2D(x: 2.0, y: 4.0) let combinedVector = vector + anotherVector vector += anotherVector
  • 118. struct Vector2D { var x = 0.0, y = 0.0 } // Custom operator - Doubling prefix operator +++ {} prefix func +++ (inout vector: Vector2D) -> Vector2D { vector += vector return vector } let doubled = +++vector
  • 119. struct Vector2D { var x = 0.0, y = 0.0 } // Custom operator - Doubling prefix operator +++ {} prefix func +++ (inout vector: Vector2D) -> Vector2D { vector += vector return vector } let doubled = +++vector
  • 120. struct Vector2D { var x = 0.0, y = 0.0 } // Custom operator - Doubling prefix operator +++ {} prefix func +++ (inout vector: Vector2D) -> Vector2D { vector += vector return vector } let doubled = +++vector
  • 121. operators are only allowed in global scope
  • 126. References • The Swift Programming Language - iBooks • Using Swift with Objective-C and Cocoa - iBooks • WWDC 2014 Sessions on Swift • Developing iOS 8 Apps with Swift - iTunesU - Stanford