Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Functional Programming Practice in Swift
Search
Hank Bao
January 10, 2016
Programming
4
110
Functional Programming Practice in Swift
Swift 函数式编程实践
2016年1月10日在 @Swift 大会上的分享
Hank Bao
January 10, 2016
Tweet
Share
More Decks by Hank Bao
See All by Hank Bao
Notes on Gamification
hankbao
0
120
Reverse Engineering: from Objective-C to Swift
hankbao
2
440
Type-safe Programming Practice in Swift
hankbao
0
110
Other Decks in Programming
See All in Programming
フロントエンドのmonorepo化と責務分離のリアーキテクト
kajitack
2
130
学習を成果に繋げるための個人開発の考え方 〜 「学習のための個人開発」のすすめ / personal project for leaning
panda_program
1
110
Infer入門
riru
4
1.6k
Constant integer division faster than compiler-generated code
herumi
2
690
decksh - a little language for decks
ajstarks
4
21k
🔨 小さなビルドシステムを作る
momeemt
1
450
Flutter로 Gemini와 MCP를 활용한 Agentic App 만들기 - 박제창 2025 I/O Extended Seoul
itsmedreamwalker
0
150
兎に角、コードレビュー
mitohato14
0
150
バイブコーディング × 設計思考
nogu66
0
130
Honoアップデート 2025年夏
yusukebe
1
840
令和最新版手のひらコンピュータ
koba789
14
8k
Google I/O recap web編 大分Web祭り2025
kponda
0
2.9k
Featured
See All Featured
Being A Developer After 40
akosma
90
590k
Faster Mobile Websites
deanohume
309
31k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.8k
The Cost Of JavaScript in 2023
addyosmani
53
8.8k
The Power of CSS Pseudo Elements
geoffreycrofte
77
5.9k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
507
140k
Designing Experiences People Love
moore
142
24k
Principles of Awesome APIs and How to Build Them.
keavy
126
17k
Automating Front-end Workflow
addyosmani
1370
200k
Six Lessons from altMBA
skipperchong
28
4k
Measuring & Analyzing Core Web Vitals
bluesmoon
9
570
VelocityConf: Rendering Performance Case Studies
addyosmani
332
24k
Transcript
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
None
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