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

Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
univalence
 
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
 

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

"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av..."Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
"Marshroute: удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Av...
AvitoTech
 
"Удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Avito)
"Удобный и расширяемый роутинг в iOS-приложении" Тимур  Юсипов (Avito)"Удобный и расширяемый роутинг в iOS-приложении" Тимур  Юсипов (Avito)
"Удобный и расширяемый роутинг в iOS-приложении" Тимур Юсипов (Avito)
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

.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 

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

VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 

Recently uploaded (20)

Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
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
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
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...
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
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...
 

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