SlideShare a Scribd company logo
1 of 39
Download to read offline
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
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

More Related Content

What's hot

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 2013aleks-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 Macrosunivalence
 
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 CLRJuan 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 fruitVaclav Pech
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data ScienceMike Anderson
 
Introduction to underscore.js
Introduction to underscore.jsIntroduction to underscore.js
Introduction to underscore.jsJitendra Zaa
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015NAVER / 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 abstractionVaclav Pech
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and DestructorsKeyur 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 qtpsiva1991
 

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
 
Clojure class
Clojure classClojure class
Clojure class
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
 
Swift Ready for Production?
Swift Ready for Production?Swift Ready for Production?
Swift Ready for Production?
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
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
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
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
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
 
Introduction to underscore.js
Introduction to underscore.jsIntroduction to underscore.js
Introduction to underscore.js
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Gpars workshop
Gpars workshopGpars workshop
Gpars workshop
 
R-Shiny Cheat sheet
R-Shiny Cheat sheetR-Shiny Cheat sheet
R-Shiny Cheat sheet
 
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
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School
 
Db connection to qtp
Db connection to qtpDb connection to qtp
Db connection to qtp
 

Viewers also liked

Swift Generics in Theory and Practice
Swift Generics in Theory and PracticeSwift Generics in Theory and Practice
Swift Generics in Theory and PracticeMichele Titolo
 
Real World Generics In Swift
Real World Generics In SwiftReal World Generics In Swift
Real World Generics In SwiftVadym Markov
 
Java Generics: a deep dive
Java Generics: a deep diveJava Generics: a deep dive
Java Generics: a deep diveBryan 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
 

Viewers also liked (20)

Generics With Swift
Generics With SwiftGenerics With Swift
Generics With Swift
 
Generics programming in Swift
Generics programming in SwiftGenerics programming in Swift
Generics programming in Swift
 
Swift Generics in Theory and Practice
Swift Generics in Theory and PracticeSwift Generics in Theory and Practice
Swift Generics in Theory and Practice
 
Real World Generics In Swift
Real World Generics In SwiftReal World Generics In Swift
Real World Generics In Swift
 
Swift 0x17 generics
Swift 0x17 genericsSwift 0x17 generics
Swift 0x17 generics
 
Java Generics: a deep dive
Java Generics: a deep diveJava Generics: a deep dive
Java Generics: a deep dive
 
"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)
"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)
"Опыт миграции между дата-центрами" Сергей Бурладян и Михаил Тюрин (Avito)
 
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
 
"Favicon на стероидах" Александр Амосов (Avito)
"Favicon на стероидах" Александр Амосов (Avito)"Favicon на стероидах" Александр Амосов (Avito)
"Favicon на стероидах" Александр Амосов (Avito)
 
"Икскод, джейсон, два скетча" Олег Фролов (Avito)
"Икскод, джейсон, два скетча" Олег Фролов (Avito)"Икскод, джейсон, два скетча" Олег Фролов (Avito)
"Икскод, джейсон, два скетча" Олег Фролов (Avito)
 
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av..."Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
 
"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)
"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)
"Опыт использования Sphinx в Ozon.ru" Игорь Чакрыгин (OZON.RU)
 
"Деплой кода процедур" Мурат Кабилов (Avito)
"Деплой кода процедур" Мурат Кабилов (Avito)"Деплой кода процедур" Мурат Кабилов (Avito)
"Деплой кода процедур" Мурат Кабилов (Avito)
 
"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)
"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)
"Подходы, используемые в разработке iOS-клиента Viber" Кирилл Лашкевич (Viber)
 
"Kotlin и rx в android" Дмитрий Воронин (Avito)
"Kotlin и rx в android" Дмитрий Воронин  (Avito)"Kotlin и rx в android" Дмитрий Воронин  (Avito)
"Kotlin и rx в android" Дмитрий Воронин (Avito)
 
"Удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Avito)
"Удобный и расширяемый роутинг в iOS-приложении" Тимур  Юсипов (Avito)"Удобный и расширяемый роутинг в iOS-приложении" Тимур  Юсипов (Avito)
"Удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Avito)
 
"Опыт участия в Microsoft Malware Classification Challenge" Михаил Трофимов ...
"Опыт участия в Microsoft Malware Classification Challenge"  Михаил Трофимов ..."Опыт участия в Microsoft Malware Classification Challenge"  Михаил Трофимов ...
"Опыт участия в Microsoft Malware Classification Challenge" Михаил Трофимов ...
 
"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)
 
"Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ...
"Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ..."Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ...
"Быстрое внедрение Sphinx на примере проекта Фоксфорд.Учебник" Антон Ковалёв ...
 
Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)
Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)
Сравнение форматов и библиотек сериализации / Антон Рыжов (Qrator Labs)
 

Similar to Advanced Swift Generics

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 MobileKonstantin Loginov
 
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
 
Short Lightening Talk
Short Lightening TalkShort Lightening Talk
Short Lightening TalkIkenna Okpala
 
iOS overview
iOS overviewiOS overview
iOS overviewgupta25
 
iOS Automation Primitives
iOS Automation PrimitivesiOS Automation Primitives
iOS Automation PrimitivesSynack
 
Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Mikhail Sosonkin
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke 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 JSIvo Andreev
 
Android development with Scala and SBT
Android development with Scala and SBTAndroid development with Scala and SBT
Android development with Scala and SBTAnton Yalyshev
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed 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-answersAkash Gawali
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
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
 

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)
 
Mobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve MobileMobile Developers Talks: Delve Mobile
Mobile Developers Talks: Delve Mobile
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
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.
 
Short Lightening Talk
Short Lightening TalkShort Lightening Talk
Short Lightening Talk
 
iOS overview
iOS overviewiOS overview
iOS overview
 
iOS Automation Primitives
iOS Automation PrimitivesiOS Automation Primitives
iOS Automation Primitives
 
Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016
 
Data herding
Data herdingData herding
Data herding
 
Data herding
Data herdingData herding
Data herding
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Iphone lecture imp
Iphone lecture  impIphone lecture  imp
Iphone lecture imp
 
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
 
Android development with Scala and SBT
Android development with Scala and SBTAndroid development with Scala and SBT
Android development with Scala and SBT
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
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...
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
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)
 

Recently uploaded

(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 

Recently uploaded (20)

DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 

Advanced Swift Generics

  • 1. Advanced Swift Generics Перейдем на <T> Max Sokolov - iOS dev @ Avito masokolov@avito.ru @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
  • 7.
  • 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