SlideShare a Scribd company logo
Advanced Swift Generics
Перейдем на <T>
Max Sokolov - iOS dev @ Avito
masokolov@avito.ru
@max_sokolov
Agenda
• The problem
• Generics in Swift
• Protocols with associated types
• Declarative type-safe UIKit
• Generics in practise
2
🤔
class Matrix<T: Choiceable where T.T == T, T: Learnable, T: Fateable>
Generic code enables you to write flexible, reusable functions
and types that can work with any type, subject to requirements
that you define. You can write code that avoids duplication and
expresses its intent in a clear, abstracted manner.
Apple docs
What for?
4
😎
Segmentation fault: 11
Advanced Swift Generics
Why?
• One team of 5 people
• 3 different apps with shared components (mostly Swift)
• 20 private CocoaPods
• Large code base (~100k)
8
[go back];
Typical api request
API Resource
/users
Raw Data
NSData?
Parsed Object
[String: String]?
Model
User?
Request Parsing
ObjectMapper
10
Implementation
@implementation DataProvider
- (void)fetch:(NSString *)resources
mappingClass:(Class)mappingClass
completion:(void(^)(NSArray<id<Mappable>> *results))completion {
// Load data...
// Parse data...
if ([mappingClass conformsToProtocol:@protocol(Mappable)]) {
id result = [mappingClass initWithDictionary:response];
completion(@[result]);
}
}
@end
11
The problem?
@implementation DataProvider
- (void)fetch:(NSString *)resources
mappingClass:(Class)mappingClass
completion:(void(^)(NSArray<id<Mappable>> *results))completion {
// Load data...
// Parse data...
if ([mappingClass conformsToProtocol:@protocol(Mappable)]) {
id result = [mappingClass initWithDictionary:response];
completion(@[result]);
}
}
@end
12
RUN TIME!
What run time means?
DataProvider *provider = [DataProvider new];
[provider fetch:@"/users"
mappingClass:[NSString class] // compiler doesn’t warn you here...
completion:^(NSArray<User *> *results) {
}];
14
You are doing it wrong with Swift
let dataProvider = DataProvider()
dataProvider.fetch("/resource", mappingClass: User.self) { result in
// code smell...
guard let users = result.values as? [User] else {
return
}
}
15
<T>
Demo
UIKit<T>?
Next generation table views
UITableView powered by generics
90% of our screens are table views
21
The problem with UITableView
• Boilerplate
• Painful when data sources are complex and dynamic
• Not type safe (dequeueReusableCellWithIdentifier etc.)
22
What table actually needs?
Model ViewModel
UITableViewCell
Deadline ;)
23
<DataType, CellType>
What if…
Line of code
let rowBuilder = TableRowBuilder<String, MyTableViewCell>(items: ["1", "2", "3"])
26
Demo
Tablet.swift
Open Source
https://github.com/maxsokolov/Tablet.swift
🚀
Tablet.swift
import Tablet
let row = TableRowBuilder<String, MyTableViewCell>(items: ["1", "2", "3"])
.action(.click) { (data) in
}
.action(.willDisplay) { (data) in
}
let section = TableSectionBuilder(headerView: nil, footerView: nil, rows: [row])
tableDirector += section
29
Generalization
NibLoadable
class MyView: UIView, NibLoadable {
}
31
let view = MyView.nibView() // view is MyView
NibLoadable / generic protocol
protocol NibLoadable {
associatedtype T: UIView
static func nibView() -> T?
}
32
extension NibLoadable where Self: UIView {
static func nibView() -> Self? {
return NSBundle(forClass: self)
.loadNibNamed(String(self), owner: nil, options: nil)
.first as? Self
}
}
NibLoadable / generic protocol
protocol NibLoadable {
associatedtype T: UIView
static func nibView() -> T?
}
33
extension NibLoadable where Self: UIView {
static func nibView() -> Self? {
return NSBundle(forClass: self)
.loadNibNamed(String(self), owner: nil, options: nil)
.first as? Self
}
}
NibLoadable / generic func
protocol NibLoadable {
static func nibView<T: UIView>(viewType type: T.Type) -> T?
}
34
extension NibLoadable where Self: UIView {
static func nibView<T: UIView>(viewType type: T.Type) -> T? {
return NSBundle.mainBundle()
.loadNibNamed(String(type), owner: nil, options: nil)
.first as? T
}
static func nibView() -> Self? {
return nibView(viewType: self)
}
}
NibLoadable / generic func
protocol NibLoadable {
static func nibView<T: UIView>(viewType type: T.Type) -> T?
}
35
extension NibLoadable where Self: UIView {
static func nibView<T: UIView>(viewType type: T.Type) -> T? {
return NSBundle.mainBundle()
.loadNibNamed(String(type), owner: nil, options: nil)
.first as! T
}
static func nibView() -> Self? {
return nibView(viewType: self)
}
}
Resume
• Currently, SDK/API’s are not generic
• Compiler is not perfect
• Can’t be used with Objective-C
• Generics help to know about potential issues earlier
• Compile-time type-safety makes your code better
36
Links
37
Covariance and Contravariance
https://www.mikeash.com/pyblog/friday-qa-2015-11-20-covariance-and-contravariance.html
Protocols with Associated Types, and How They Got That Way
http://www.slideshare.net/alexis_gallagher/protocols-with-associated-types-and-how-they-got-that-way
Why Associated Types?
http://www.russbishop.net/swift-why-associated-types
Tablet.swift
https://github.com/maxsokolov/Tablet.swift
THANK YOU!
QUESTIONS?
Max Sokolov - iOS dev @ Avito
@max_sokolov
https://github.com/maxsokolov
Ad

More Related Content

What's hot (20)

Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application
Andy Bunce
 
Clojure class
Clojure classClojure class
Clojure class
Aysylu Greenberg
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
aleks-f
 
Swift Ready for Production?
Swift Ready for Production?Swift Ready for Production?
Swift Ready for Production?
Crispy Mountain
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
Tomasz Kowalczewski
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
univalence
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
Tomasz Kowalczewski
 
Mejores Practicas en SQL Server - Seguridad, Conectividad y CLR
Mejores Practicas en SQL Server - Seguridad, Conectividad y CLRMejores Practicas en SQL Server - Seguridad, Conectividad y CLR
Mejores Practicas en SQL Server - Seguridad, Conectividad y CLR
Juan Fabian
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
Radim Pavlicek
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
Mike Anderson
 
Introduction to underscore.js
Introduction to underscore.jsIntroduction to underscore.js
Introduction to underscore.js
Jitendra Zaa
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
scalaconfjp
 
Gpars workshop
Gpars workshopGpars workshop
Gpars workshop
Vaclav Pech
 
R-Shiny Cheat sheet
R-Shiny Cheat sheetR-Shiny Cheat sheet
R-Shiny Cheat sheet
Dr. Volkan OBAN
 
GPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstractionGPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstraction
Vaclav Pech
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School
Flink Forward
 
Db connection to qtp
Db connection to qtpDb connection to qtp
Db connection to qtp
siva1991
 
Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application
Andy Bunce
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
aleks-f
 
Swift Ready for Production?
Swift Ready for Production?Swift Ready for Production?
Swift Ready for Production?
Crispy Mountain
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
univalence
 
Mejores Practicas en SQL Server - Seguridad, Conectividad y CLR
Mejores Practicas en SQL Server - Seguridad, Conectividad y CLRMejores Practicas en SQL Server - Seguridad, Conectividad y CLR
Mejores Practicas en SQL Server - Seguridad, Conectividad y CLR
Juan Fabian
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
Mike Anderson
 
Introduction to underscore.js
Introduction to underscore.jsIntroduction to underscore.js
Introduction to underscore.js
Jitendra Zaa
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
GPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstractionGPars howto - when to use which concurrency abstraction
GPars howto - when to use which concurrency abstraction
Vaclav Pech
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School
Flink Forward
 
Db connection to qtp
Db connection to qtpDb connection to qtp
Db connection to qtp
siva1991
 

Viewers also liked (20)

Generics With Swift
Generics With SwiftGenerics With Swift
Generics With Swift
Hirakawa Akira
 
Generics programming in Swift
Generics programming in SwiftGenerics programming in Swift
Generics programming in Swift
Vijaya Prakash Kandel
 
Swift Generics in Theory and Practice
Swift Generics in Theory and PracticeSwift Generics in Theory and Practice
Swift Generics in Theory and Practice
Michele Titolo
 
Real World Generics In Swift
Real World Generics In SwiftReal World Generics In Swift
Real World Generics In Swift
Vadym Markov
 
Swift 0x17 generics
Swift 0x17 genericsSwift 0x17 generics
Swift 0x17 generics
Hyun Jin Moon
 
Java Generics: a deep dive
Java Generics: a deep diveJava Generics: a deep dive
Java Generics: a deep dive
Bryan Basham
 
"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)
"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)
"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)
AvitoTech
 
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
AvitoTech
 
"Favicon на стероидах" Александр Амосов (Avito)
"Favicon на стероидах" Александр Амосов (Avito)"Favicon на стероидах" Александр Амосов (Avito)
"Favicon на стероидах" Александр Амосов (Avito)
AvitoTech
 
"Икскод, джейсон, два скетча" Олег Фролов (Avito)
"Икскод, джейсон, два скетча" Олег Фролов (Avito)"Икскод, джейсон, два скетча" Олег Фролов (Avito)
"Икскод, джейсон, два скетча" Олег Фролов (Avito)
AvitoTech
 
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av..."Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
AvitoTech
 
"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)
"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)
"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)
AvitoTech
 
"Деплой кода процедур" Мурат Кабилов (Avito)
"Деплой кода процедур" Мурат Кабилов (Avito)"Деплой кода процедур" Мурат Кабилов (Avito)
"Деплой кода процедур" Мурат Кабилов (Avito)
AvitoTech
 
"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)
"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)
"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)
AvitoTech
 
"Kotlin и rx в android" Дмитрий Воронин (Avito)
"Kotlin и rx в android" Дмитрий Воронин  (Avito)"Kotlin и rx в android" Дмитрий Воронин  (Avito)
"Kotlin и rx в android" Дмитрий Воронин (Avito)
AvitoTech
 
"Удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Avito)
"Удобный и расширяемый роутинг в iOS-приложении" Тимур  Юсипов (Avito)"Удобный и расширяемый роутинг в iOS-приложении" Тимур  Юсипов (Avito)
"Удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Avito)
AvitoTech
 
"Опыт участия в Microsoft Malware Classification Challenge" Михаил Трофимов ...
"Опыт участия в Microsoft Malware Classification Challenge"  Михаил Трофимов ..."Опыт участия в Microsoft Malware Classification Challenge"  Михаил Трофимов ...
"Опыт участия в Microsoft Malware Classification Challenge" Михаил Трофимов ...
AvitoTech
 
"Basis.js - Production Ready SPA Framework" Сергей Мелюков (Avito)
"Basis.js - Production Ready SPA Framework" Сергей Мелюков (Avito)"Basis.js - Production Ready SPA Framework" Сергей Мелюков (Avito)
"Basis.js - Production Ready SPA Framework" Сергей Мелюков (Avito)
AvitoTech
 
"Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ...
"Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ..."Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ...
"Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ...
AvitoTech
 
Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)
Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)
Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)
Ontico
 
Swift Generics in Theory and Practice
Swift Generics in Theory and PracticeSwift Generics in Theory and Practice
Swift Generics in Theory and Practice
Michele Titolo
 
Real World Generics In Swift
Real World Generics In SwiftReal World Generics In Swift
Real World Generics In Swift
Vadym Markov
 
Java Generics: a deep dive
Java Generics: a deep diveJava Generics: a deep dive
Java Generics: a deep dive
Bryan Basham
 
"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)
"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)
"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)
AvitoTech
 
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
AvitoTech
 
"Favicon на стероидах" Александр Амосов (Avito)
"Favicon на стероидах" Александр Амосов (Avito)"Favicon на стероидах" Александр Амосов (Avito)
"Favicon на стероидах" Александр Амосов (Avito)
AvitoTech
 
"Икскод, джейсон, два скетча" Олег Фролов (Avito)
"Икскод, джейсон, два скетча" Олег Фролов (Avito)"Икскод, джейсон, два скетча" Олег Фролов (Avito)
"Икскод, джейсон, два скетча" Олег Фролов (Avito)
AvitoTech
 
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av..."Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
AvitoTech
 
"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)
"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)
"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)
AvitoTech
 
"Деплой кода процедур" Мурат Кабилов (Avito)
"Деплой кода процедур" Мурат Кабилов (Avito)"Деплой кода процедур" Мурат Кабилов (Avito)
"Деплой кода процедур" Мурат Кабилов (Avito)
AvitoTech
 
"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)
"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)
"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)
AvitoTech
 
"Kotlin и rx в android" Дмитрий Воронин (Avito)
"Kotlin и rx в android" Дмитрий Воронин  (Avito)"Kotlin и rx в android" Дмитрий Воронин  (Avito)
"Kotlin и rx в android" Дмитрий Воронин (Avito)
AvitoTech
 
"Удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Avito)
"Удобный и расширяемый роутинг в iOS-приложении" Тимур  Юсипов (Avito)"Удобный и расширяемый роутинг в iOS-приложении" Тимур  Юсипов (Avito)
"Удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Avito)
AvitoTech
 
"Опыт участия в Microsoft Malware Classification Challenge" Михаил Трофимов ...
"Опыт участия в Microsoft Malware Classification Challenge"  Михаил Трофимов ..."Опыт участия в Microsoft Malware Classification Challenge"  Михаил Трофимов ...
"Опыт участия в Microsoft Malware Classification Challenge" Михаил Трофимов ...
AvitoTech
 
"Basis.js - Production Ready SPA Framework" Сергей Мелюков (Avito)
"Basis.js - Production Ready SPA Framework" Сергей Мелюков (Avito)"Basis.js - Production Ready SPA Framework" Сергей Мелюков (Avito)
"Basis.js - Production Ready SPA Framework" Сергей Мелюков (Avito)
AvitoTech
 
"Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ...
"Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ..."Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ...
"Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ...
AvitoTech
 
Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)
Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)
Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)
Ontico
 
Ad

Similar to Advanced Swift Generics (20)

How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)
Giuseppe Filograno
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve Mobile
Konstantin Loginov
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
Docent Education
 
Short Lightening Talk
Short Lightening TalkShort Lightening Talk
Short Lightening Talk
Ikenna Okpala
 
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Skills Matter
 
iOS overview
iOS overviewiOS overview
iOS overview
gupta25
 
Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016
Mikhail Sosonkin
 
iOS Automation Primitives
iOS Automation PrimitivesiOS Automation Primitives
iOS Automation Primitives
Synack
 
Data herding
Data herdingData herding
Data herding
unbracketed
 
Data herding
Data herdingData herding
Data herding
unbracketed
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
Luke Donnet
 
Iphone lecture imp
Iphone lecture  impIphone lecture  imp
Iphone lecture imp
Pragati Singh
 
Flux QL - Nexgen Management of Time Series Inspired by JS
Flux QL - Nexgen Management of Time Series Inspired by JSFlux QL - Nexgen Management of Time Series Inspired by JS
Flux QL - Nexgen Management of Time Series Inspired by JS
Ivo Andreev
 
Android development with Scala and SBT
Android development with Scala and SBTAndroid development with Scala and SBT
Android development with Scala and SBT
Anton Yalyshev
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y
 
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
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
Skills Matter
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
Akash Gawali
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 
iPhone development from a Java perspective (Jazoon '09)
iPhone development from a Java perspective (Jazoon '09)iPhone development from a Java perspective (Jazoon '09)
iPhone development from a Java perspective (Jazoon '09)
Netcetera
 
How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)
Giuseppe Filograno
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve Mobile
Konstantin Loginov
 
Short Lightening Talk
Short Lightening TalkShort Lightening Talk
Short Lightening Talk
Ikenna Okpala
 
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Skills Matter
 
iOS overview
iOS overviewiOS overview
iOS overview
gupta25
 
Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016
Mikhail Sosonkin
 
iOS Automation Primitives
iOS Automation PrimitivesiOS Automation Primitives
iOS Automation Primitives
Synack
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
Luke Donnet
 
Flux QL - Nexgen Management of Time Series Inspired by JS
Flux QL - Nexgen Management of Time Series Inspired by JSFlux QL - Nexgen Management of Time Series Inspired by JS
Flux QL - Nexgen Management of Time Series Inspired by JS
Ivo Andreev
 
Android development with Scala and SBT
Android development with Scala and SBTAndroid development with Scala and SBT
Android development with Scala and SBT
Anton Yalyshev
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y
 
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
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
Akash Gawali
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 
iPhone development from a Java perspective (Jazoon '09)
iPhone development from a Java perspective (Jazoon '09)iPhone development from a Java perspective (Jazoon '09)
iPhone development from a Java perspective (Jazoon '09)
Netcetera
 
Ad

Recently uploaded (20)

Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Resistance measurement and cfd test on darpa subboff model
Resistance measurement and cfd test on darpa subboff modelResistance measurement and cfd test on darpa subboff model
Resistance measurement and cfd test on darpa subboff model
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
How to use nRF24L01 module with Arduino
How to use nRF24L01 module with ArduinoHow to use nRF24L01 module with Arduino
How to use nRF24L01 module with Arduino
CircuitDigest
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Data Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptxData Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptx
RushaliDeshmukh2
 
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIHlecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
Abodahab
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
How to use nRF24L01 module with Arduino
How to use nRF24L01 module with ArduinoHow to use nRF24L01 module with Arduino
How to use nRF24L01 module with Arduino
CircuitDigest
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Data Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptxData Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptx
RushaliDeshmukh2
 
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIHlecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
lecture5.pptxJHKGJFHDGTFGYIUOIUIPIOIPUOHIYGUYFGIH
Abodahab
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 

Advanced Swift Generics

  • 1. Advanced Swift Generics Перейдем на <T> Max Sokolov - iOS dev @ Avito [email protected] @max_sokolov
  • 2. Agenda • The problem • Generics in Swift • Protocols with associated types • Declarative type-safe UIKit • Generics in practise 2
  • 3. 🤔 class Matrix<T: Choiceable where T.T == T, T: Learnable, T: Fateable>
  • 4. Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner. Apple docs What for? 4
  • 8. Why? • One team of 5 people • 3 different apps with shared components (mostly Swift) • 20 private CocoaPods • Large code base (~100k) 8
  • 10. Typical api request API Resource /users Raw Data NSData? Parsed Object [String: String]? Model User? Request Parsing ObjectMapper 10
  • 11. Implementation @implementation DataProvider - (void)fetch:(NSString *)resources mappingClass:(Class)mappingClass completion:(void(^)(NSArray<id<Mappable>> *results))completion { // Load data... // Parse data... if ([mappingClass conformsToProtocol:@protocol(Mappable)]) { id result = [mappingClass initWithDictionary:response]; completion(@[result]); } } @end 11
  • 12. The problem? @implementation DataProvider - (void)fetch:(NSString *)resources mappingClass:(Class)mappingClass completion:(void(^)(NSArray<id<Mappable>> *results))completion { // Load data... // Parse data... if ([mappingClass conformsToProtocol:@protocol(Mappable)]) { id result = [mappingClass initWithDictionary:response]; completion(@[result]); } } @end 12
  • 14. What run time means? DataProvider *provider = [DataProvider new]; [provider fetch:@"/users" mappingClass:[NSString class] // compiler doesn’t warn you here... completion:^(NSArray<User *> *results) { }]; 14
  • 15. You are doing it wrong with Swift let dataProvider = DataProvider() dataProvider.fetch("/resource", mappingClass: User.self) { result in // code smell... guard let users = result.values as? [User] else { return } } 15
  • 16. <T>
  • 17. Demo
  • 19. Next generation table views UITableView powered by generics
  • 20. 90% of our screens are table views
  • 21. 21
  • 22. The problem with UITableView • Boilerplate • Painful when data sources are complex and dynamic • Not type safe (dequeueReusableCellWithIdentifier etc.) 22
  • 23. What table actually needs? Model ViewModel UITableViewCell Deadline ;) 23
  • 26. Line of code let rowBuilder = TableRowBuilder<String, MyTableViewCell>(items: ["1", "2", "3"]) 26
  • 27. Demo
  • 29. Tablet.swift import Tablet let row = TableRowBuilder<String, MyTableViewCell>(items: ["1", "2", "3"]) .action(.click) { (data) in } .action(.willDisplay) { (data) in } let section = TableSectionBuilder(headerView: nil, footerView: nil, rows: [row]) tableDirector += section 29
  • 31. NibLoadable class MyView: UIView, NibLoadable { } 31 let view = MyView.nibView() // view is MyView
  • 32. NibLoadable / generic protocol protocol NibLoadable { associatedtype T: UIView static func nibView() -> T? } 32 extension NibLoadable where Self: UIView { static func nibView() -> Self? { return NSBundle(forClass: self) .loadNibNamed(String(self), owner: nil, options: nil) .first as? Self } }
  • 33. NibLoadable / generic protocol protocol NibLoadable { associatedtype T: UIView static func nibView() -> T? } 33 extension NibLoadable where Self: UIView { static func nibView() -> Self? { return NSBundle(forClass: self) .loadNibNamed(String(self), owner: nil, options: nil) .first as? Self } }
  • 34. NibLoadable / generic func protocol NibLoadable { static func nibView<T: UIView>(viewType type: T.Type) -> T? } 34 extension NibLoadable where Self: UIView { static func nibView<T: UIView>(viewType type: T.Type) -> T? { return NSBundle.mainBundle() .loadNibNamed(String(type), owner: nil, options: nil) .first as? T } static func nibView() -> Self? { return nibView(viewType: self) } }
  • 35. NibLoadable / generic func protocol NibLoadable { static func nibView<T: UIView>(viewType type: T.Type) -> T? } 35 extension NibLoadable where Self: UIView { static func nibView<T: UIView>(viewType type: T.Type) -> T? { return NSBundle.mainBundle() .loadNibNamed(String(type), owner: nil, options: nil) .first as! T } static func nibView() -> Self? { return nibView(viewType: self) } }
  • 36. Resume • Currently, SDK/API’s are not generic • Compiler is not perfect • Can’t be used with Objective-C • Generics help to know about potential issues earlier • Compile-time type-safety makes your code better 36
  • 37. Links 37 Covariance and Contravariance https://www.mikeash.com/pyblog/friday-qa-2015-11-20-covariance-and-contravariance.html Protocols with Associated Types, and How They Got That Way http://www.slideshare.net/alexis_gallagher/protocols-with-associated-types-and-how-they-got-that-way Why Associated Types? http://www.russbishop.net/swift-why-associated-types Tablet.swift https://github.com/maxsokolov/Tablet.swift
  • 39. QUESTIONS? Max Sokolov - iOS dev @ Avito @max_sokolov https://github.com/maxsokolov