SlideShare a Scribd company logo
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Advanced functional
programming
Pragmatic use cases for Monads
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Functional Programming
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
First-class and higher-order functions
let double: (Int) -> Int = { $0 * 2 }
func apply(value: Int, function: (Int) -> Int) -> Int {
return function(value)
}
let result = apply(value: 4, function: double)
// result == 8
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Some properties
• A function is said to be pure if it produces no side-effects and its
return value only depends on its arguments
• An expression is said to be referentially transparent if it can be
replaced by its value without altering the program’s behavior
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Optionals
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Some very familiar code
var data: [String]?
// ...
let result = data?.first?.uppercased()
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Some very familiar code
var data: [String]?
// ...
let result = data?.first?.uppercased()
The operator ?. allows us to declare a workflow that will be executed
in order, and will prematurely stop if a nil value is encountered
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Let’s try to write the code for ?.
extension Optional {
func ?.<U>(lhs: Wrapped?, rhs: (Wrapped) -> U) -> U? {
switch self {
case .some(let value):
return .some(rhs(value))
case .none:
return nil
}
}
}
Disclaimer : this is a simplified
case for methods with no
arguments
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Arrays
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Let’s manipulate an Array
let data: [Int] = [0, 1, 2]
let result = data.map { $0 * 2 }.map { $0 * $0 }
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Let’s manipulate an Array
let data: [Int] = [0, 1, 2]
let result = data.map { $0 * 2 }.map { $0 * $0 }
Same thing here: the function map allows us to declare a workflow
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
A possible implementation for map
extension Array {
func map<U>(_ transform: (Element) -> U) -> [U] {
var result: [U] = []
for e in self {
result.append(transform(e))
}
return result
}
}
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Functions
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Let’s compose functions
let double: (Int) -> Int = { x in x * 2 }
let square: (Int) -> Int = { x in x * x }
infix operator • : AdditionPrecedence
func •<T, U, V>(lhs: (U) -> V, rhs: (T) -> U) -> ((T) -> V) {
return { t in lhs(rhs(t)) }
}
let result = (double • square)(4) // result == 32
Disclaimer : @escaping
attributes have been omitted
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Let’s compose functions
let double: (Int) -> Int = { x in x * 2 }
let square: (Int) -> Int = { x in x * x }
infix operator • : AdditionPrecedence
func •<T, U, V>(lhs: (U) -> V, rhs: (T) -> U) -> ((T) -> V) {
return { t in lhs(rhs(t)) }
}
let result = (double • square)(4) // result == 32
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
We have three similar behaviors,
yet backed by very different
implementation
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
What are the common parts?
• They contain value(s) inside a context
• They add new features to existing types
• They provide an interface to transform/map the inner value
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Monad: intuitive definition
• Wraps a type inside a context
• Provides a mechanism to create a workflow of transforms
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Minimal Monad
struct Monad<T> {
let value: T
// additional data
static func just(_ value: T) -> Monad<T> {
return self.init(value: value)
}
}
infix operator >>> : AdditionPrecedence
func >>> <U, V>(lhs: Monad<U>, rhs: (U) -> Monad<V>) -> Monad<V> {
// specific combination code
}
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Let’s look at an application
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Writer Monad
• We have an application that does a lot of numerical calculation
• It’s hard to keep track of how values have been computed
• We would like to have a way to store a value along with a log of all
the transformation it went through
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Writer Monad
struct Logged<T> {
let value: T
let logs: [String]
private init(value: T) {
self.value = value
self.logs = ["initialized with value: (self.value)"]
}
static func just(_ value: T) -> Logged<T> {
return Logged(value: value)
}
}
func >>> <U, V>(lhs: Logged<U>, rhs: (U) -> Logged<V>) -> Logged<V> {
let computation = rhs(lhs.value)
return Logged<V>(value: computation.value, logs: lhs.logs + computation.logs)
}
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Writer Monad
func square(_ value: Int) -> Logged<Int> {
let result = value * value
return Logged(value: result, log: "(value) was squared, result: (result)")
}
func halve(_ value: Int) -> Logged<Int> {
let result = value / 2
return Logged(value: result, log: "(value) was halved, result: (result)")
}
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Writer Monad
let computation = .just(4) >>> square >>> halve
print(computation)
// Logged<Int>(value: 8, logs: ["initialized with value: 4",
"4 was squared, result: 16", "16 was halved, result: 8"])
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Now let’s think architecture
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Now let’s think architecture
We can model the current state of an app with a struct
struct AppState {
let userName: String
let currentSong: URL?
let favoriteSongs: [URL]
}
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Now let’s think architecture
We can model the action our app emits, in a declarative fashion
protocol Action { }
struct UpdateUserNameAction: Action {
let newUserName: String
}
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Now let’s think architecture
We can react to those actions in a functional way
infix operator >>> : AdditionPrecedence
func >>>(appstate: AppState?, action: Action) -> AppState {
var appstate = appstate ?? AppState()
switch action {
case let newUserNameAction as UpdateUserNameAction:
appstate.userName = newUserNameAction.newUserName
default:
break
}
return appstate
}
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Now let’s think architecture
And finally we put everything together
AppState() >>> UpdateUserNameAction(newUserName: "Vincent")
// AppState(userName: Optional("Vincent"), currentSong: nil,
favoriteSongs: [])
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
ReSwift
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
ReSwift
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Minimal example
import ReSwift
struct AppState: StateType {
// ... app state properties here ...
}
func appReducer(action: Action, state: AppState?) -> AppState {
// ...
}
let store = Store(
reducer: appReducer,
state: AppState(), // You may also start with `nil`
middleware: []) // Middlewares are optional
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
A more « real life » example
func appReducer(action: Action, state: AppState?) -> AppState {
return AppState(
navigationState: navigationReducer(state?.navigationState, action: action),
authenticationState: authenticationReducer(state?.authenticationState, action: action),
repositories: repositoriesReducer(state?.repositories, action: action),
bookmarks: bookmarksReducer(state?.bookmarks, action: action)
)
}
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
A more « real life » example
func authenticationReducer(state: AuthenticationState?, action: Action) -> AuthenticationState {
var state = state ?? initialAuthenticationState()
switch action {
case _ as ReSwiftInit:
break
case let action as SetOAuthURL:
state.oAuthURL = action.oAuthUrl
case let action as UpdateLoggedInState:
state.loggedInState = action.loggedInState
default:
break
}
return state
}
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
A more « real life » example
let store: Store<AppState> = Store(reducer: appReducer, state: nil) // in AppDelegate file
class BookmarksViewController: UIViewController, StoreSubscriber {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
store.subscribe(self) { subcription in
return subcription.select { state in return state.bookmarks }
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
store.unsubscribe(self)
}
func newState(state: StateType?) {
// update view
}
}
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Advantages
• Reducers are pure (stateless) functions, easy to test
• Code review of business logic is easier
• A « demo » mode of the app is easy to implement (UI Testing)
• Deep-linking becomes a trivial use-case
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Drawbacks
• Not a silver bullet, a bit overkill for web-service driven apps
• Requires to create a lot of types (but at least not ObjC types)
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Questions ?
Vincent Pradeilles - CocoaHeads Lyon - 21/09/17
Bibliography
• https://en.wikipedia.org/wiki/Monad_(functional_programming)
• https://www.youtube.com/watch?v=ZhuHCtR3xq8 (Brian Beckman: Don't fear
the Monad)
• https://academy.realm.io/posts/slug-raheel-ahmad-using-monads-functional-
paradigms-in-practice-functors-patterns-swift/ (Using Monads and Other
Functional Paradigms in Practice)
• https://github.com/orakaro/Swift-monad-Maybe-Reader-and-Try
• https://academy.realm.io/posts/benji-encz-unidirectional-data-flow-swift/
(Unidirectional Data Flow: Shrinking Massive View Controllers)
Ad

More Related Content

What's hot (20)

Map kit light
Map kit lightMap kit light
Map kit light
CocoaHeads France
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
Hadziq Fabroyir
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDC
Tomohiro Kumagai
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
CocoaHeads France
 
operator overloading
operator overloadingoperator overloading
operator overloading
Nishant Joshi
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
Rai University
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
François Sarradin
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
ramya marichamy
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Codemotion
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
Outware Mobile
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
Codemotion
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
Luis Atencio
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
Hermann Hueck
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
Sebastiano Armeli
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
Thomas Roch
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
SmartLogic
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpreted
Martha Schumann
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
Hadziq Fabroyir
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDC
Tomohiro Kumagai
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
CocoaHeads France
 
operator overloading
operator overloadingoperator overloading
operator overloading
Nishant Joshi
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
Rai University
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Codemotion
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
Outware Mobile
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
Codemotion
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
Luis Atencio
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
Hermann Hueck
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
Sebastiano Armeli
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
Thomas Roch
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
SmartLogic
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpreted
Martha Schumann
 

Viewers also liked (11)

CONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANECONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANE
CocoaHeads France
 
Quoi de neuf dans iOS 10.3
Quoi de neuf dans iOS 10.3Quoi de neuf dans iOS 10.3
Quoi de neuf dans iOS 10.3
CocoaHeads France
 
iOS Coding Best Practices
iOS Coding Best PracticesiOS Coding Best Practices
iOS Coding Best Practices
Jean-Luc David
 
Handle the error
Handle the errorHandle the error
Handle the error
CocoaHeads France
 
Design like a developer
Design like a developerDesign like a developer
Design like a developer
CocoaHeads France
 
Make Acccessibility Great Again
Make Acccessibility Great AgainMake Acccessibility Great Again
Make Acccessibility Great Again
Geoffrey Goutallier
 
Super combinators
Super combinatorsSuper combinators
Super combinators
CocoaHeads France
 
Cocoaheads
CocoaheadsCocoaheads
Cocoaheads
Benjamin Pisano
 
L'intégration continue avec Bitrise
L'intégration continue avec BitriseL'intégration continue avec Bitrise
L'intégration continue avec Bitrise
CocoaHeads France
 
Tout savoir pour devenir Freelance
Tout savoir pour devenir FreelanceTout savoir pour devenir Freelance
Tout savoir pour devenir Freelance
Florent Douine
 
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
Carol Smith
 
CONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANECONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANE
CocoaHeads France
 
iOS Coding Best Practices
iOS Coding Best PracticesiOS Coding Best Practices
iOS Coding Best Practices
Jean-Luc David
 
L'intégration continue avec Bitrise
L'intégration continue avec BitriseL'intégration continue avec Bitrise
L'intégration continue avec Bitrise
CocoaHeads France
 
Tout savoir pour devenir Freelance
Tout savoir pour devenir FreelanceTout savoir pour devenir Freelance
Tout savoir pour devenir Freelance
Florent Douine
 
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
AI and Machine Learning Demystified by Carol Smith at Midwest UX 2017
Carol Smith
 
Ad

Similar to Advanced functional programing in Swift (20)

Redux training
Redux trainingRedux training
Redux training
dasersoft
 
operator overloading
operator overloadingoperator overloading
operator overloading
Sorath Peetamber
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
InfluxData
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
kanaka vardhini
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
bhargavi804095
 
Swift on Raspberry Pi
Swift on Raspberry PiSwift on Raspberry Pi
Swift on Raspberry Pi
Sally Shepard
 
«Управление логикой переходов между экранами приложения с помощью координатор...
«Управление логикой переходов между экранами приложения с помощью координатор...«Управление логикой переходов между экранами приложения с помощью координатор...
«Управление логикой переходов между экранами приложения с помощью координатор...
Mail.ru Group
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, Hereford
Kit Eason
 
ApplicationCoordinator для навигации между экранами / Павел Гуров (Avito)
ApplicationCoordinator для навигации между экранами / Павел Гуров (Avito)ApplicationCoordinator для навигации между экранами / Павел Гуров (Avito)
ApplicationCoordinator для навигации между экранами / Павел Гуров (Avito)
Ontico
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
Andrey Karpov
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей Родионов
Yandex
 
State manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexState manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to Vuex
Commit University
 
Introducing Vuex in your project
Introducing Vuex in your projectIntroducing Vuex in your project
Introducing Vuex in your project
Denny Biasiolli
 
Materi Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdfMateri Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdf
exiabreak
 
Android Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyondAndroid Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyond
Ramon Ribeiro Rabello
 
React redux
React reduxReact redux
React redux
Michel Perez
 
How to use redux with react hooks in react native application
How to use redux with react hooks in react native applicationHow to use redux with react hooks in react native application
How to use redux with react hooks in react native application
Katy Slemon
 
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesAnalyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
PVS-Studio
 
Redux training
Redux trainingRedux training
Redux training
dasersoft
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
Anais Dotis-Georgiou & Faith Chikwekwe [InfluxData] | Top 10 Hurdles for Flux...
InfluxData
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
bhargavi804095
 
Swift on Raspberry Pi
Swift on Raspberry PiSwift on Raspberry Pi
Swift on Raspberry Pi
Sally Shepard
 
«Управление логикой переходов между экранами приложения с помощью координатор...
«Управление логикой переходов между экранами приложения с помощью координатор...«Управление логикой переходов между экранами приложения с помощью координатор...
«Управление логикой переходов между экранами приложения с помощью координатор...
Mail.ru Group
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, Hereford
Kit Eason
 
ApplicationCoordinator для навигации между экранами / Павел Гуров (Avito)
ApplicationCoordinator для навигации между экранами / Павел Гуров (Avito)ApplicationCoordinator для навигации между экранами / Павел Гуров (Avito)
ApplicationCoordinator для навигации между экранами / Павел Гуров (Avito)
Ontico
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
Andrey Karpov
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей Родионов
Yandex
 
State manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexState manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to Vuex
Commit University
 
Introducing Vuex in your project
Introducing Vuex in your projectIntroducing Vuex in your project
Introducing Vuex in your project
Denny Biasiolli
 
Materi Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdfMateri Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdf
exiabreak
 
Android Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyondAndroid Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyond
Ramon Ribeiro Rabello
 
How to use redux with react hooks in react native application
How to use redux with react hooks in react native applicationHow to use redux with react hooks in react native application
How to use redux with react hooks in react native application
Katy Slemon
 
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesAnalyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
PVS-Studio
 
Ad

More from Vincent Pradeilles (8)

On-Boarding New Engineers
On-Boarding New EngineersOn-Boarding New Engineers
On-Boarding New Engineers
Vincent Pradeilles
 
The underestimated power of KeyPaths
The underestimated power of KeyPathsThe underestimated power of KeyPaths
The underestimated power of KeyPaths
Vincent Pradeilles
 
Solving callback hell with good old function composition
Solving callback hell with good old function compositionSolving callback hell with good old function composition
Solving callback hell with good old function composition
Vincent Pradeilles
 
Taking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryTaking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with Sourcery
Vincent Pradeilles
 
How to build a debug view almost for free
How to build a debug view almost for freeHow to build a debug view almost for free
How to build a debug view almost for free
Vincent Pradeilles
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
 
Implementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional ProgramingImplementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional Programing
Vincent Pradeilles
 
Property Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become JavaProperty Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become Java
Vincent Pradeilles
 
The underestimated power of KeyPaths
The underestimated power of KeyPathsThe underestimated power of KeyPaths
The underestimated power of KeyPaths
Vincent Pradeilles
 
Solving callback hell with good old function composition
Solving callback hell with good old function compositionSolving callback hell with good old function composition
Solving callback hell with good old function composition
Vincent Pradeilles
 
Taking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryTaking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with Sourcery
Vincent Pradeilles
 
How to build a debug view almost for free
How to build a debug view almost for freeHow to build a debug view almost for free
How to build a debug view almost for free
Vincent Pradeilles
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
 
Implementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional ProgramingImplementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional Programing
Vincent Pradeilles
 
Property Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become JavaProperty Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become Java
Vincent Pradeilles
 

Recently uploaded (20)

Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
Imma Valls Bernaus
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Foundation Models for Time Series : A Survey
Foundation Models for Time Series : A SurveyFoundation Models for Time Series : A Survey
Foundation Models for Time Series : A Survey
jayanthkalyanam1
 
Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025
fs4635986
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
Imma Valls Bernaus
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Foundation Models for Time Series : A Survey
Foundation Models for Time Series : A SurveyFoundation Models for Time Series : A Survey
Foundation Models for Time Series : A Survey
jayanthkalyanam1
 
Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025
fs4635986
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 

Advanced functional programing in Swift

  • 1. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Advanced functional programming Pragmatic use cases for Monads
  • 2. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Functional Programming
  • 3. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 First-class and higher-order functions let double: (Int) -> Int = { $0 * 2 } func apply(value: Int, function: (Int) -> Int) -> Int { return function(value) } let result = apply(value: 4, function: double) // result == 8
  • 4. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Some properties • A function is said to be pure if it produces no side-effects and its return value only depends on its arguments • An expression is said to be referentially transparent if it can be replaced by its value without altering the program’s behavior
  • 5. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Optionals
  • 6. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Some very familiar code var data: [String]? // ... let result = data?.first?.uppercased()
  • 7. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Some very familiar code var data: [String]? // ... let result = data?.first?.uppercased() The operator ?. allows us to declare a workflow that will be executed in order, and will prematurely stop if a nil value is encountered
  • 8. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Let’s try to write the code for ?. extension Optional { func ?.<U>(lhs: Wrapped?, rhs: (Wrapped) -> U) -> U? { switch self { case .some(let value): return .some(rhs(value)) case .none: return nil } } } Disclaimer : this is a simplified case for methods with no arguments
  • 9. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Arrays
  • 10. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Let’s manipulate an Array let data: [Int] = [0, 1, 2] let result = data.map { $0 * 2 }.map { $0 * $0 }
  • 11. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Let’s manipulate an Array let data: [Int] = [0, 1, 2] let result = data.map { $0 * 2 }.map { $0 * $0 } Same thing here: the function map allows us to declare a workflow
  • 12. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 A possible implementation for map extension Array { func map<U>(_ transform: (Element) -> U) -> [U] { var result: [U] = [] for e in self { result.append(transform(e)) } return result } }
  • 13. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Functions
  • 14. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Let’s compose functions let double: (Int) -> Int = { x in x * 2 } let square: (Int) -> Int = { x in x * x } infix operator • : AdditionPrecedence func •<T, U, V>(lhs: (U) -> V, rhs: (T) -> U) -> ((T) -> V) { return { t in lhs(rhs(t)) } } let result = (double • square)(4) // result == 32 Disclaimer : @escaping attributes have been omitted
  • 15. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Let’s compose functions let double: (Int) -> Int = { x in x * 2 } let square: (Int) -> Int = { x in x * x } infix operator • : AdditionPrecedence func •<T, U, V>(lhs: (U) -> V, rhs: (T) -> U) -> ((T) -> V) { return { t in lhs(rhs(t)) } } let result = (double • square)(4) // result == 32
  • 16. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 We have three similar behaviors, yet backed by very different implementation
  • 17. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 What are the common parts? • They contain value(s) inside a context • They add new features to existing types • They provide an interface to transform/map the inner value
  • 18. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Monad: intuitive definition • Wraps a type inside a context • Provides a mechanism to create a workflow of transforms
  • 19. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Minimal Monad struct Monad<T> { let value: T // additional data static func just(_ value: T) -> Monad<T> { return self.init(value: value) } } infix operator >>> : AdditionPrecedence func >>> <U, V>(lhs: Monad<U>, rhs: (U) -> Monad<V>) -> Monad<V> { // specific combination code }
  • 20. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Let’s look at an application
  • 21. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Writer Monad • We have an application that does a lot of numerical calculation • It’s hard to keep track of how values have been computed • We would like to have a way to store a value along with a log of all the transformation it went through
  • 22. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Writer Monad struct Logged<T> { let value: T let logs: [String] private init(value: T) { self.value = value self.logs = ["initialized with value: (self.value)"] } static func just(_ value: T) -> Logged<T> { return Logged(value: value) } } func >>> <U, V>(lhs: Logged<U>, rhs: (U) -> Logged<V>) -> Logged<V> { let computation = rhs(lhs.value) return Logged<V>(value: computation.value, logs: lhs.logs + computation.logs) }
  • 23. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Writer Monad func square(_ value: Int) -> Logged<Int> { let result = value * value return Logged(value: result, log: "(value) was squared, result: (result)") } func halve(_ value: Int) -> Logged<Int> { let result = value / 2 return Logged(value: result, log: "(value) was halved, result: (result)") }
  • 24. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Writer Monad let computation = .just(4) >>> square >>> halve print(computation) // Logged<Int>(value: 8, logs: ["initialized with value: 4", "4 was squared, result: 16", "16 was halved, result: 8"])
  • 25. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Now let’s think architecture
  • 26. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Now let’s think architecture We can model the current state of an app with a struct struct AppState { let userName: String let currentSong: URL? let favoriteSongs: [URL] }
  • 27. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Now let’s think architecture We can model the action our app emits, in a declarative fashion protocol Action { } struct UpdateUserNameAction: Action { let newUserName: String }
  • 28. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Now let’s think architecture We can react to those actions in a functional way infix operator >>> : AdditionPrecedence func >>>(appstate: AppState?, action: Action) -> AppState { var appstate = appstate ?? AppState() switch action { case let newUserNameAction as UpdateUserNameAction: appstate.userName = newUserNameAction.newUserName default: break } return appstate }
  • 29. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Now let’s think architecture And finally we put everything together AppState() >>> UpdateUserNameAction(newUserName: "Vincent") // AppState(userName: Optional("Vincent"), currentSong: nil, favoriteSongs: [])
  • 30. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 ReSwift
  • 31. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 ReSwift
  • 32. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Minimal example import ReSwift struct AppState: StateType { // ... app state properties here ... } func appReducer(action: Action, state: AppState?) -> AppState { // ... } let store = Store( reducer: appReducer, state: AppState(), // You may also start with `nil` middleware: []) // Middlewares are optional
  • 33. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 A more « real life » example func appReducer(action: Action, state: AppState?) -> AppState { return AppState( navigationState: navigationReducer(state?.navigationState, action: action), authenticationState: authenticationReducer(state?.authenticationState, action: action), repositories: repositoriesReducer(state?.repositories, action: action), bookmarks: bookmarksReducer(state?.bookmarks, action: action) ) }
  • 34. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 A more « real life » example func authenticationReducer(state: AuthenticationState?, action: Action) -> AuthenticationState { var state = state ?? initialAuthenticationState() switch action { case _ as ReSwiftInit: break case let action as SetOAuthURL: state.oAuthURL = action.oAuthUrl case let action as UpdateLoggedInState: state.loggedInState = action.loggedInState default: break } return state }
  • 35. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 A more « real life » example let store: Store<AppState> = Store(reducer: appReducer, state: nil) // in AppDelegate file class BookmarksViewController: UIViewController, StoreSubscriber { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) store.subscribe(self) { subcription in return subcription.select { state in return state.bookmarks } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) store.unsubscribe(self) } func newState(state: StateType?) { // update view } }
  • 36. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Advantages • Reducers are pure (stateless) functions, easy to test • Code review of business logic is easier • A « demo » mode of the app is easy to implement (UI Testing) • Deep-linking becomes a trivial use-case
  • 37. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Drawbacks • Not a silver bullet, a bit overkill for web-service driven apps • Requires to create a lot of types (but at least not ObjC types)
  • 38. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Questions ?
  • 39. Vincent Pradeilles - CocoaHeads Lyon - 21/09/17 Bibliography • https://en.wikipedia.org/wiki/Monad_(functional_programming) • https://www.youtube.com/watch?v=ZhuHCtR3xq8 (Brian Beckman: Don't fear the Monad) • https://academy.realm.io/posts/slug-raheel-ahmad-using-monads-functional- paradigms-in-practice-functors-patterns-swift/ (Using Monads and Other Functional Paradigms in Practice) • https://github.com/orakaro/Swift-monad-Maybe-Reader-and-Try • https://academy.realm.io/posts/benji-encz-unidirectional-data-flow-swift/ (Unidirectional Data Flow: Shrinking Massive View Controllers)