SlideShare a Scribd company logo
SWIFT
@HANKBAO
IM
WHAT
WHAT
Functional programming is a programming paradigm
1. treats computation as the evaluation of mathematical functions
2. avoids changing-state and mutable data
— Wikipedia
PARADIGM
Functional programming in Swift
THINK
IMPERATIVE: MACHINE
let nums = [1, 2, 3, 4, 5, 6, 7]
var strs = [String]()
for var i = 0; i < nums.count; ++i {
strs.append(String(nums[i]))
}
DECLARATIVE: MATHEMATICS
let nums = [1, 2, 3, 4, 5, 6, 7]
let strs = nums.map(String.init)
WHY
CURRY
CURRY
func x(a: A, b: B, c: C) -> E
func x(a: A) -> (b: B) -> (c: C) -> E
CURRY
struct User {
func login(password: String)
}
let passwd = "@Swift"
let usr = User()
usr.login(passwd)
CURRY
struct User {
func login(password: String)
}
let passwd = "@Swift"
let usr = User()
User.login(usr)(passwd)
CURRY
usr.login(passwd)
||
User.login(usr)(passwd)
CURRY IN PRACTICE
struct User {
func name() -> String
}
let collation: UILocalizedIndexedCollation = ...
let sorted = collation.sortedArrayFromArray(users,
collationStringSelector: "name")
CURRY IN PRACTICE
class Wrapper<T>: NSObject {
let payload: T
let localization: (T) -> () -> String
@objc func localizable() -> NSString {
return localization(payload)()
}
static var selector: Selector {
return "localizable"
}
}
CURRY IN PRACTICE
let wrappers = users.map {
Wrapper(payload: $0, localization: User.name)
}
let sorted = collation.sortedArrayFromArray(wrappers,
collationStringSelector: Wrapper<User>.selector)
FUNCTIONAL ABSTRACTION
OPTIONAL
enum Optional<T> {
case None
case Some(T)
}
OPTIONAL
func map<U>(f: T -> U) -> U?
func flatMap<U>(f: T -> U?) -> U?
let date: NSDate? = ...
let formatter: NSDateFormatter = ...
let dateString = date.map(formatter.stringFromDate)
ARRAY
func map<T>(t: Self.Generator.Element -> T) -> [T]
func flatMap<S: SequenceType>
(t: Self.Generator.Element -> S) -> [S.Generator.Element]
MONAD<?>
MONAD<ASYNC>
PROMISE
class Promise<T> {
func then<U>(body: T -> U) -> Promise<U>
func then<U>(body: T -> Promise<U>) -> Promise<U>
}
PROMISE
class Promise<T> {
func map<U>(body: T -> U) -> Promise<U>
func flatMap<U>(body: T -> Promise<U>) -> Promise<U>
}
OBSERVABLE
class Observable<T> {
func map<U>(body: T -> U) -> Observable<U>
func flatMap<U>(body: T -> Observable<U>) -> Observable<U>
}
MONAD IN PRACTICE
ASYNC CALLBACK
(value: T?, error: ErrorType?) -> Void
ASYNC CALLBACK
(value: T?, error: ErrorType?) -> Void
if let error = error {
// handle error
} else if let value = value {
// handle value
} else {
// all nil?
}
// all non-nil?!
RESULT
enum Result<Value> {
case Failure(ErrorType)
case Success(Value)
}
RESULT
(result: Result<T>) -> Void
switch result {
case let .Error(error):
// handle error
case let .Success(value):
// handle value
}
RESULT
enum Result<Value> {
func map<T>(...) -> Result<T> {
...
}
func flatMap<T>(...) -> Result<T> {
...
}
}
RESULT
func flatMap<T>(@noescape transform: Value throws -> Result<T>) rethrows -> Result<T> {
switch self {
case let .Failure(error):
return .Failure(error)
case let .Success(value):
return try transform(value)
}
}
func map<T>(@noescape transform: Value throws -> T) rethrows -> Result<T> {
return try flatMap { .Success(try transform($0)) }
}
RESULT
func toImage(data: NSData) -> Result<UIImage>
func addAlpha(image: UIImage) -> Result<UIImage>
func roundCorner(image: UIImage) -> Result<UIImage>
func applyBlur(image: UIImage) -> Result<UIImage>
RESULT
toImage(data)
.flatMap(addAlpha)
.flatMap(roundCorner)
.flatMap(applyBlur)
REFERENCE
▸ Wikipedia
▸ Haskell Wiki
▸ Functional Programming in Swift
▸ objc.io
THANKS
Q & A

More Related Content

PPT
Module 2 topic 2 notes
PPTX
Stack - Data Structure
PPT
Stack Data Structure V1.0
PDF
XKE Typeclass
ODP
2.3 implicits
PPTX
2.5 function transformations
PPTX
2.3 graphs of functions
Module 2 topic 2 notes
Stack - Data Structure
Stack Data Structure V1.0
XKE Typeclass
2.3 implicits
2.5 function transformations
2.3 graphs of functions

What's hot (20)

PDF
Data structures stacks
PPTX
2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
PPTX
2 d array(part 2) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
PPTX
2.6 transformations
PDF
Stack push pop
PDF
Linked list searching deleting inserting
PPTX
Data structure by Digvijay
PPTX
Stack and queue
PDF
Advanced
PPT
Stack and queue
PPT
03 stacks and_queues_using_arrays
PPT
Circular queues
PPT
Infix prefix postfix
PPTX
Application of Stack - Yadraj Meena
PPTX
STACKS IN DATASTRUCTURE
PPT
Stack application
PPTX
Stack_Application_Infix_Prefix.pptx
PDF
Bcsl 033 data and file structures lab s5-3
PPTX
Clojure to Slang
Data structures stacks
2 d array(part 1) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
2 d array(part 2) || 2D ARRAY FUNCTION WRITING || GET 100% MARKS IN CBSE CS
2.6 transformations
Stack push pop
Linked list searching deleting inserting
Data structure by Digvijay
Stack and queue
Advanced
Stack and queue
03 stacks and_queues_using_arrays
Circular queues
Infix prefix postfix
Application of Stack - Yadraj Meena
STACKS IN DATASTRUCTURE
Stack application
Stack_Application_Infix_Prefix.pptx
Bcsl 033 data and file structures lab s5-3
Clojure to Slang
Ad

Viewers also liked (20)

PDF
Diigo 網路閱讀狂人必備知識分享工具
PPT
RTF
Fietscaisson omschrijving a
PPT
Florida-Nicholas and Kenneth
PDF
Fiko Store
PPTX
Shakespeare ppt
PDF
Wayne Pua SM Portfolio
PPT
Crisis management
DOCX
Worksheet Listening
PDF
Bản tin Hoa Sen số 12
PDF
Two sides of diversity
PPT
North Carolina-Clarence and Isaiah
ODP
PPT
Louisiana- Brady and Paul
PPT
El cos huma
PPT
Third grade class newsletter
PPT
Electronic Report Distribution with OM Plus RM
PPTX
Honeymoon
PPT
North Carolina- Luke and Mark
PDF
La revolució científica!
Diigo 網路閱讀狂人必備知識分享工具
Fietscaisson omschrijving a
Florida-Nicholas and Kenneth
Fiko Store
Shakespeare ppt
Wayne Pua SM Portfolio
Crisis management
Worksheet Listening
Bản tin Hoa Sen số 12
Two sides of diversity
North Carolina-Clarence and Isaiah
Louisiana- Brady and Paul
El cos huma
Third grade class newsletter
Electronic Report Distribution with OM Plus RM
Honeymoon
North Carolina- Luke and Mark
La revolució científica!
Ad

Similar to Functional programming in Swift (20)

PPTX
Functional Programming in Swift
PDF
7 Habits For a More Functional Swift
PDF
An introduction to functional programming with Swift
PDF
Cocoa heads 09112017
PDF
Hardcore functional programming
PDF
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
PDF
Functional Programming Principles & Patterns
PPTX
Functional Programming in Javascript - IL Tech Talks week
PDF
Functional programming in Scala
PDF
Effecting Pure Change - How anything ever gets done in functional programming...
PPTX
FRP: What does "declarative" mean
PPTX
Thinking Functionally with JavaScript
PDF
Christian Gill ''Functional programming for the people''
PPTX
Why functional programming in C# & F#
PDF
Ankara Jug - Practical Functional Programming with Scala
PDF
Monads in Swift
PDF
Functional programming
PDF
Introduction to Functional Programming (w/ JS)
ODP
Functional programming
PDF
Swift Rocks #2: Going functional
Functional Programming in Swift
7 Habits For a More Functional Swift
An introduction to functional programming with Swift
Cocoa heads 09112017
Hardcore functional programming
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Functional Programming Principles & Patterns
Functional Programming in Javascript - IL Tech Talks week
Functional programming in Scala
Effecting Pure Change - How anything ever gets done in functional programming...
FRP: What does "declarative" mean
Thinking Functionally with JavaScript
Christian Gill ''Functional programming for the people''
Why functional programming in C# & F#
Ankara Jug - Practical Functional Programming with Scala
Monads in Swift
Functional programming
Introduction to Functional Programming (w/ JS)
Functional programming
Swift Rocks #2: Going functional

Recently uploaded (20)

PDF
RMMM.pdf make it easy to upload and study
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Cell Structure & Organelles in detailed.
PPTX
Institutional Correction lecture only . . .
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Classroom Observation Tools for Teachers
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Sports Quiz easy sports quiz sports quiz
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Cell Types and Its function , kingdom of life
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Complications of Minimal Access Surgery at WLH
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
RMMM.pdf make it easy to upload and study
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Abdominal Access Techniques with Prof. Dr. R K Mishra
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Cell Structure & Organelles in detailed.
Institutional Correction lecture only . . .
Module 4: Burden of Disease Tutorial Slides S2 2025
Classroom Observation Tools for Teachers
GDM (1) (1).pptx small presentation for students
Sports Quiz easy sports quiz sports quiz
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Microbial disease of the cardiovascular and lymphatic systems
Cell Types and Its function , kingdom of life
Microbial diseases, their pathogenesis and prophylaxis
Complications of Minimal Access Surgery at WLH
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Final Presentation General Medicine 03-08-2024.pptx

Functional programming in Swift