SlideShare a Scribd company logo
Swift done right
IVAN ĐIKIĆ
INTRO
• value types
• protocols
• functions as first class citizens
• generics
4 MAIN PILLARS OF SWIFT
SIDE NOTE: LET vs. VAR
let theAnswer = 42 // IMMUTABLE
var theAnswer = 42 // MUTABLE
• var defines ordinary variable
• let defines constant v
01VALUE TYPES
SWIFT TYPES
• value types
• instances keeps unique copy of its data
• struct, enum or tuple
• array, dictionary, set …
• reference types
• instances share a single copy of the data
• class
• Swift STL - 90% value types
EXAMPLE: value vs. reference
// Value type example
struct S { var data: Int = -1 }
var a = S()
var b = a
a.data = 42
print("(a.data), (b.data)") // prints "42, -1"
// Reference type example
class C { var data: Int = -1 }
var x = C()
var y = x
x.data = 42
print("(x.data), (y.data)") // prints "42, 42"
WHY VALUE TYPES
• reason about code
• performance
• threadsafe
HOW TO CHOOSE BETWEEN THE TWO
• value types (==)
• you want copies to have independent state
• data will be used in code across multiple threads
• examples
• data model layer
• API routers (e.g. Alamofire Router)
HOW TO CHOOSE BETWEEN TWO
• reference types (===, ==)
• you want copies to have mutable, shared state
• Cocoa
• examples
• UIKit subclasses
• API Managers
• Singletons
02HIGHER ORDER FUNCTIONS
“The highest level of
abstraction possible,
and no lower than the
level at which you are
expert.”
IN SWIFT EVERYTHING IS A FUNCTION
• +, -, …
• you can pass them around
• you can apply them partially
• higher order functions
• map, filter, reduce and friends
EXAMPLE: MAP
let moneyArray = [10, 20, 30, 40]
var stringArray: [String] = []
// Naive approach
for money in moneyArray {
stringArray.append("(money)$")
}
// Swift approach
stringArray = moneyArray.map { (money: Int) -> String in
return "(money)$"
}
EXAMPLE: FILTER
let moneyArray = [10, 20, 30, 40]
var filteredArray : [Int] = []
// Naive approach
for money in moneyArray {
if (money > 30) {
filteredArray += [money]
}
}
// Swift approach
filteredArray = moneyArray
.filter { (money: Int) -> Bool in
return money > 30
}
EXAMPLE: REDUCE
let moneyArray = [10, 20, 30, 40]
var sum = 0
// Naive approach
for money in moneyArray {
sum = sum + money
}
// Swift approach
sum = moneyArray
.reduce(0, combine: { (accumulator: Int, money: Int) -> Int in
return accumulator + money
})
IN SWIFT EVERYTHING IS A FUNCTION
• can be reduced to a simple for in loop
• nothing inherently different or special about how they work
• they can elevate your perspective about common
programming tasks
03PROTOCOLS
SWIFT IS A PROTOCOL ORIENTED
PROGRAMMING LANGUAGE
• single inheritance
• inheritance only for classes
• STL includes 54 public protocols
• can do - “able” - `RawRepresentable`
• is a - “type” - `CollectionType`
• can be - “convertible” - `CustomStringConvertible`
• prefer composition instead of inheritance
EXAMPLE: inheritance
UIVIEWCONTROLLER
ROOT VIEW CONTROLLER
PROGRESSABLE VIEW CONTROLLER
LOGIN VIEW CONTROLLER
EXAMPLE: composition
LOGIN VIEW CONTROLLER PROGRESSABLE XY
EXAMPLE: protocol
protocol Progressable: NSObjectProtocol {
func showLoading(message: String?)
.
.
.
}
final class LoginViewController: UIViewController, Progressable {
func showLoading(message: String?) {
}
.
.
.
}
PROTOCOL EXTENSIONS
• extremely powerful feature
• useful for providing a default implementations
EXAMPLE: protocol extensions
protocol Progressable: NSObjectProtocol {
func showLoading(message: String?)
.
.
.
}
extension Progressable where Self: UIViewController {
func showLoading(msg:String?) {
SVProgressHUD.showWithStatus(
msg,
maskType: SVProgressHUDMaskType.Gradient)
}
.
.
.
}
final class LoginViewController: UIViewController, Progressable {
...
}
04GENERICS
GENERICS
• PROBLEM:
• write code that is type agnostic
• SOLUTION
• <T>
EXAMPLE: generic approach
protocol NumericType {
func +(lhs: Self, rhs: Self) -> Self
}
extension Float : NumericType {}
extension Int : NumericType {}
func sum<T: NumericType>(x x:T, y:T) -> T {
return x + y
}
sum(x: 1, y: 2)
sum(x: 1.5, y: 2.1)
EXAMPLE: Array
public struct Array<Element> : ... {
.
.
.
}
var stringsArray = ["A","B","C"]
05OPTIONALS
SWIFT’S WAY OF REPRESENTING NOTHINGNESS
• is a type that can represent
• wrapped value
• nothing
• is a concept that does exists in other languages (Haskell, Scala)
• is a type that supports usage of higher order functions on it
EXAMPLE: optional value
var perhapsInt: Int?
• WRONG:
• “This is an Int, which is optional”
• RIGHT:
• “This is an Optional, which may or may not hold and Int”
Q&A

More Related Content

PPT
PPT
Php course-in-navimumbai
PDF
Scala for the web Lightning Talk
PPTX
OOP in Scala
KEY
CS442 - Rogue: A Scala DSL for MongoDB
TXT
Htmlgraficcode
PDF
PHP object calisthenics
PPT
CSS for basic learner
Php course-in-navimumbai
Scala for the web Lightning Talk
OOP in Scala
CS442 - Rogue: A Scala DSL for MongoDB
Htmlgraficcode
PHP object calisthenics
CSS for basic learner

Viewers also liked (20)

PPTX
Unit e adobe dreamweaver cs6
PPTX
Intro to Swift techitout
PDF
Infinum Android Talks #18 - Create fun lists by Ivan Marić
PDF
HTML5 & Friends
PDF
Object Oriented Programming Ch3 SRP, DIP, ISP
PDF
Slack introduction
PPTX
Swift programming language
KEY
キーボードで完結!ハイスピード Xcodeコーディング
PDF
Swift
PDF
Apple Swift API Design Guideline
PDF
Object Oriented Programming in Swift Ch2 Polymorphism, OCP, LSP
PPT
Swift-Programming Part 1
PPT
Introduction To Web Design with Dreamweaver Basics
PPTX
Bootstrap [part 1]
PDF
Swift Programming Language
PPTX
Unit a adobe dreamweaver cs6
PDF
Object Oriented Programming in Swift Ch0 - Encapsulation
PDF
20 Facts about Swift programming language
DOC
Basic Web Design In Dreamweaver
PDF
Introduction to Swift programming language.
Unit e adobe dreamweaver cs6
Intro to Swift techitout
Infinum Android Talks #18 - Create fun lists by Ivan Marić
HTML5 & Friends
Object Oriented Programming Ch3 SRP, DIP, ISP
Slack introduction
Swift programming language
キーボードで完結!ハイスピード Xcodeコーディング
Swift
Apple Swift API Design Guideline
Object Oriented Programming in Swift Ch2 Polymorphism, OCP, LSP
Swift-Programming Part 1
Introduction To Web Design with Dreamweaver Basics
Bootstrap [part 1]
Swift Programming Language
Unit a adobe dreamweaver cs6
Object Oriented Programming in Swift Ch0 - Encapsulation
20 Facts about Swift programming language
Basic Web Design In Dreamweaver
Introduction to Swift programming language.
Ad

Similar to Infinum iOS Talks #1 - Swift done right by Ivan Dikic (20)

PDF
All Aboard The Scala-to-PureScript Express!
PDF
Introduction to Swift 2
PDF
The Swift Compiler and Standard Library
PDF
Deep Dive Into Swift
PDF
Real World Generics In Swift
PDF
Quick swift tour
PPTX
Scala fundamentals
PDF
Kotlin Basics - Apalon Kotlin Sprint Part 2
PDF
An introduction to functional programming with Swift
PDF
Scala for Java Programmers
PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
PDF
An Introduction to Scala for Java Developers
PPTX
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
PDF
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
PDF
Scala in Places API
PPTX
Should i Go there
PDF
Functional programming with F#
PDF
Spring Day | Spring and Scala | Eberhard Wolff
PDF
Scala and Spring
PDF
Scala intro workshop
All Aboard The Scala-to-PureScript Express!
Introduction to Swift 2
The Swift Compiler and Standard Library
Deep Dive Into Swift
Real World Generics In Swift
Quick swift tour
Scala fundamentals
Kotlin Basics - Apalon Kotlin Sprint Part 2
An introduction to functional programming with Swift
Scala for Java Programmers
BCS SPA 2010 - An Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Scala in Places API
Should i Go there
Functional programming with F#
Spring Day | Spring and Scala | Eberhard Wolff
Scala and Spring
Scala intro workshop
Ad

More from Infinum (20)

PDF
Infinum Android Talks #20 - Making your Android apps fast like Blue Runner an...
PDF
Infinum Android Talks #20 - DiffUtil
PDF
Infinum Android Talks #20 - Benefits of using Kotlin
PDF
Infinum iOS Talks #4 - Making our VIPER more reactive
PDF
Infinum iOS Talks #4 - Making your Swift networking code more awesome with Re...
PDF
Infinum Android Talks #13 - Using ViewDragHelper
PDF
Infinum Android Talks #14 - Log4j
PDF
Infinum Android Talks #9 - Making your app location-aware
PDF
Infinum Android Talks #14 - Gradle plugins
PDF
Infinum Android Talks #14 - Facebook for Android API
PDF
Infinum Android Talks #19 - Stop wasting time fixing bugs with TDD by Domagoj...
PDF
Infinum Android Talks #18 - In-app billing by Ivan Marić
PDF
Infinum Android Talks #18 - How to cache like a boss by Željko Plesac
PDF
Infinum iOS Talks #2 - VIPER for everybody by Damjan Vujaklija
PDF
Infinum iOS Talks #2 - Xamarin by Ivan Đikić
PDF
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
PDF
Infinum iOS Talks #1 - Becoming an iOS developer swiftly by Vedran Burojevic
PDF
Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
PDF
Infinum Android Talks #17 - A quest for WebSockets by Zeljko Plesac
PDF
Infinum Android Talks #17 - Developing an Android library by Dino Kovac
Infinum Android Talks #20 - Making your Android apps fast like Blue Runner an...
Infinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - Benefits of using Kotlin
Infinum iOS Talks #4 - Making our VIPER more reactive
Infinum iOS Talks #4 - Making your Swift networking code more awesome with Re...
Infinum Android Talks #13 - Using ViewDragHelper
Infinum Android Talks #14 - Log4j
Infinum Android Talks #9 - Making your app location-aware
Infinum Android Talks #14 - Gradle plugins
Infinum Android Talks #14 - Facebook for Android API
Infinum Android Talks #19 - Stop wasting time fixing bugs with TDD by Domagoj...
Infinum Android Talks #18 - In-app billing by Ivan Marić
Infinum Android Talks #18 - How to cache like a boss by Željko Plesac
Infinum iOS Talks #2 - VIPER for everybody by Damjan Vujaklija
Infinum iOS Talks #2 - Xamarin by Ivan Đikić
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Becoming an iOS developer swiftly by Vedran Burojevic
Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - A quest for WebSockets by Zeljko Plesac
Infinum Android Talks #17 - Developing an Android library by Dino Kovac

Recently uploaded (20)

PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
System and Network Administration Chapter 2
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
System and Network Administraation Chapter 3
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
L1 - Introduction to python Backend.pptx
PPTX
history of c programming in notes for students .pptx
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Navsoft: AI-Powered Business Solutions & Custom Software Development
Design an Analysis of Algorithms I-SECS-1021-03
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
How to Choose the Right IT Partner for Your Business in Malaysia
System and Network Administration Chapter 2
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Online Work Permit System for Fast Permit Processing
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
How Creative Agencies Leverage Project Management Software.pdf
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Odoo Companies in India – Driving Business Transformation.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
System and Network Administraation Chapter 3
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
L1 - Introduction to python Backend.pptx
history of c programming in notes for students .pptx
Wondershare Filmora 15 Crack With Activation Key [2025
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus

Infinum iOS Talks #1 - Swift done right by Ivan Dikic

  • 3. • value types • protocols • functions as first class citizens • generics 4 MAIN PILLARS OF SWIFT
  • 4. SIDE NOTE: LET vs. VAR let theAnswer = 42 // IMMUTABLE var theAnswer = 42 // MUTABLE • var defines ordinary variable • let defines constant v
  • 6. SWIFT TYPES • value types • instances keeps unique copy of its data • struct, enum or tuple • array, dictionary, set … • reference types • instances share a single copy of the data • class • Swift STL - 90% value types
  • 7. EXAMPLE: value vs. reference // Value type example struct S { var data: Int = -1 } var a = S() var b = a a.data = 42 print("(a.data), (b.data)") // prints "42, -1" // Reference type example class C { var data: Int = -1 } var x = C() var y = x x.data = 42 print("(x.data), (y.data)") // prints "42, 42"
  • 8. WHY VALUE TYPES • reason about code • performance • threadsafe
  • 9. HOW TO CHOOSE BETWEEN THE TWO • value types (==) • you want copies to have independent state • data will be used in code across multiple threads • examples • data model layer • API routers (e.g. Alamofire Router)
  • 10. HOW TO CHOOSE BETWEEN TWO • reference types (===, ==) • you want copies to have mutable, shared state • Cocoa • examples • UIKit subclasses • API Managers • Singletons
  • 12. “The highest level of abstraction possible, and no lower than the level at which you are expert.”
  • 13. IN SWIFT EVERYTHING IS A FUNCTION • +, -, … • you can pass them around • you can apply them partially • higher order functions • map, filter, reduce and friends
  • 14. EXAMPLE: MAP let moneyArray = [10, 20, 30, 40] var stringArray: [String] = [] // Naive approach for money in moneyArray { stringArray.append("(money)$") } // Swift approach stringArray = moneyArray.map { (money: Int) -> String in return "(money)$" }
  • 15. EXAMPLE: FILTER let moneyArray = [10, 20, 30, 40] var filteredArray : [Int] = [] // Naive approach for money in moneyArray { if (money > 30) { filteredArray += [money] } } // Swift approach filteredArray = moneyArray .filter { (money: Int) -> Bool in return money > 30 }
  • 16. EXAMPLE: REDUCE let moneyArray = [10, 20, 30, 40] var sum = 0 // Naive approach for money in moneyArray { sum = sum + money } // Swift approach sum = moneyArray .reduce(0, combine: { (accumulator: Int, money: Int) -> Int in return accumulator + money })
  • 17. IN SWIFT EVERYTHING IS A FUNCTION • can be reduced to a simple for in loop • nothing inherently different or special about how they work • they can elevate your perspective about common programming tasks
  • 19. SWIFT IS A PROTOCOL ORIENTED PROGRAMMING LANGUAGE • single inheritance • inheritance only for classes • STL includes 54 public protocols • can do - “able” - `RawRepresentable` • is a - “type” - `CollectionType` • can be - “convertible” - `CustomStringConvertible` • prefer composition instead of inheritance
  • 20. EXAMPLE: inheritance UIVIEWCONTROLLER ROOT VIEW CONTROLLER PROGRESSABLE VIEW CONTROLLER LOGIN VIEW CONTROLLER
  • 21. EXAMPLE: composition LOGIN VIEW CONTROLLER PROGRESSABLE XY
  • 22. EXAMPLE: protocol protocol Progressable: NSObjectProtocol { func showLoading(message: String?) . . . } final class LoginViewController: UIViewController, Progressable { func showLoading(message: String?) { } . . . }
  • 23. PROTOCOL EXTENSIONS • extremely powerful feature • useful for providing a default implementations
  • 24. EXAMPLE: protocol extensions protocol Progressable: NSObjectProtocol { func showLoading(message: String?) . . . } extension Progressable where Self: UIViewController { func showLoading(msg:String?) { SVProgressHUD.showWithStatus( msg, maskType: SVProgressHUDMaskType.Gradient) } . . . } final class LoginViewController: UIViewController, Progressable { ... }
  • 26. GENERICS • PROBLEM: • write code that is type agnostic • SOLUTION • <T>
  • 27. EXAMPLE: generic approach protocol NumericType { func +(lhs: Self, rhs: Self) -> Self } extension Float : NumericType {} extension Int : NumericType {} func sum<T: NumericType>(x x:T, y:T) -> T { return x + y } sum(x: 1, y: 2) sum(x: 1.5, y: 2.1)
  • 28. EXAMPLE: Array public struct Array<Element> : ... { . . . } var stringsArray = ["A","B","C"]
  • 30. SWIFT’S WAY OF REPRESENTING NOTHINGNESS • is a type that can represent • wrapped value • nothing • is a concept that does exists in other languages (Haskell, Scala) • is a type that supports usage of higher order functions on it
  • 31. EXAMPLE: optional value var perhapsInt: Int? • WRONG: • “This is an Int, which is optional” • RIGHT: • “This is an Optional, which may or may not hold and Int”
  • 32. Q&A