Optional є одним з фундаментальних типів у Swift. На жаль, незважаючи на його поширеність, чимало розробників не звертають уваги на можливості, приховані у цьому типі, або використовують його недоречно. Все це призводить до порушень основних принципів програмування, а також нехтує деякими потужними можливостями, доступними у Swift. Крім того, цей тип дозволяє розглянути важливі концепти, які зроблять рутинну роботу з Optional і схожими типами, ефективнішою та зручнішою.
Під час доповіді ми відповімо на питання чому та як слід оминати optional binding. Розглянемо приклад з код-рев'ю і зробимо рефакторинг у фунціональному стилі щоб побачити недоліки та переваги такого підходу у Swift. Це надасть нам змогу дослідити як Optional впливає на DI та обробку помилок і які є альтернативи до стандартних технік, доступних у Swift.
http://uamobile.org/uk/topics/optional-tips-and-tricks
85. What is Optional?
• Optional is container for a reason: it preserves optional
context
86. What is Optional?
• Optional is container for a reason: it preserves optional
context
• Optional ensures that null values aren’t passed as
arguments to functions that can’t handle them
87. What is Optional?
• Optional is container for a reason: it preserves optional
context
• Optional ensures that null values aren’t passed as
arguments to functions that can’t handle them
• Optional interface provides a handful mechanism for
applying functions to such values in a pipeline
88. What is Optional?
• Optional is container for a reason: it preserves optional
context
• Optional ensures that null values aren’t passed as
arguments to functions that can’t handle them
• Optional interface provides a handful mechanism for
applying functions to such values in a pipeline
• Optional binding applies a function to a value stored in an
Optional, not binds the value to a variable
91. Optional context
• The absence of a value is OK, not an error
• One doesn’t care why Optional computation’s value is
absent
92. Optional context
• The absence of a value is OK, not an error
• One doesn’t care why Optional computation’s value is
absent
• Optional isn’t designed for error handling
96. Error handling
• It’s better to handle errors or they will handle you
• try-catch is the default technique and can be
improved
97. Error handling
• It’s better to handle errors or they will handle you
• try-catch is the default technique and can be
improved
• Please, don’t use Optional for error handling
131. What is Result?
enum Result<Success, Error> {
/// A success, storing `Success`
case success(Success)
/// A failure, storing `Error`
case failure(Error)
...
}
apple/swift-evolution
139. Error handling (async)
• Reactive/promise primitives are preferable over closures*
* beware the memory management
140. Error handling (async)
• Reactive/promise primitives are preferable over closures*
• Allow you to chain multiple async operations in a pipeline
* beware the memory management
141. Error handling (async)
• Reactive/promise primitives are preferable over closures*
• Allow you to chain multiple async operations in a pipeline
• ReactiveSwift has typed errors in primitives
* beware the memory management
160. Initializer injection
• In Swift a type must be completely initialized before
being used
• Can’t be used with UIKit objects initialized from a xib or
a storyboard…
161. Initializer injection
• In Swift a type must be completely initialized before
being used
• Can’t be used with UIKit objects initialized from a xib or
a storyboard…
• Avoid injections in UIViewController
162. Initializer injection
• In Swift a type must be completely initialized before
being used
• Can’t be used with UIKit objects initialized from a xib or
a storyboard…
• Avoid injections in UIViewController
• UIViewController is a view, not a controller*
*Swift Heroes 2018.
Krzysztof Zablocki — Maintainable iOS Architectures
165. Initializer injection
• Some types might have a lot of dependencies
• Try to use protocol composition in order to avoid large
initializers*
*Krzysztof Zablocki — Using protocol compositon
for dependency injection
172. Property injection
• Introduces Optional in a client
• Forces optional binding all over the client
• Avoid implicitly unwrapped Optional if you forced to use
property injection
173. Property injection
• Introduces Optional in a client
• Forces optional binding all over the client
• Avoid implicitly unwrapped Optional if you forced to use
property injection
• Implicitly unwrapped Optional is a code smell in pure
Swift
184. Injection patterns
• Initializer injection is a default pattern in Swift
• Try to avoid property injection
• If a project has both Swift and Objective-C code try to
annotate Nullability in Objective-C types
188. Monad
• Is a design pattern (data type in pure functional
languages)
189. Monad
• Is a design pattern (data type in pure functional
languages)
• Is extremely abstract and generic
190. Monad
• Is a design pattern (data type in pure functional
languages)
• Is extremely abstract and generic
• Defined by mathematical laws
191. Monad
• Is a design pattern (data type in pure functional
languages)
• Is extremely abstract and generic
• Defined by mathematical laws
• Due to high abstraction level it’s pretty complex to explain
what a monad is
239. Partial application
* the statement is only true for functional languages like Haskell.
Partial application is a bit complex :)
240. Partial application
Supplying fewer than the total
number of arguments in a curried
function is referred to as partial
application*
* the statement is only true for functional languages like Haskell.
Partial application is a bit complex :)
241. Optional functions
• Performing partial application of a function using our
optional operators returns an optional function
242. Optional functions
• Performing partial application of a function using our
optional operators returns an optional function
ciImage <*> curry(image)
257. But wait…
• Functional style allows to stay DRY
• Swift’s type system doesn’t allow generic monads
258. But wait…
• Functional style allows to stay DRY
• Swift’s type system doesn’t allow generic monads
• Each monad needs its own implementation of eDSL
259. But wait…
• Functional style allows to stay DRY
• Swift’s type system doesn’t allow generic monads
• Each monad needs its own implementation of eDSL
• …
260. But wait…
• Functional style allows to stay DRY
• Swift’s type system doesn’t allow generic monads
• Each monad needs its own implementation of eDSL
• …
• PROFIT!!11
264. But why?
• Introduces new powerful tools
• Encourages modularity and composition
• Encourages careful treatment of types and mutable
states
265. But why?
• Introduces new powerful tools
• Encourages modularity and composition
• Encourages careful treatment of types and mutable
states
• Fun!
271. Deep cuts
• Jeremy Gibbons, Oege de Moor; The Fun of
Programming (ISBN: 978-0333992852)
272. Deep cuts
• Jeremy Gibbons, Oege de Moor; The Fun of
Programming (ISBN: 978-0333992852)
• Harold Abelson, Gerald Jay Sussman, Julie Sussman;
Structure and Interpretation of Computer Programs
(ISBN: 978-0262510875)