SlideShare a Scribd company logo
Adopting Swift Generics
Перейдем на <T>
Max Sokolov - iOS dev @ Avito
masokolov@avito.ru
max_sokolov
2
3
World’s 3rd
Biggest
Classifieds Site
35m
users
per month
500k
items
per day
100k
deals
Agenda
• Dynamic type-casting problem
• Generics in Swift
• Protocols with associated types
• Declarative type-safe UIKit
• Livecoding!
4
🤔
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?
6
😎
Segmentation fault: 11
Adopting Swift Generics
Why?
• One team of 5 people
• 3 different apps with shared components (mostly Swift)
• 20 private CocoaPods
• Large code base (~100k)
10
[go back];
Typical api request
API Resource
/users
Raw Data
NSData?
Parsed Object
[String: String]?
Model
User?
Request Parsing
ObjectMapper
12
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
13
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
14
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) {
}];
16
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
}
}
17
<T>
Demo
UIKit<T>?
UITableView powered by generics
90% of our screens are table views
23
Problems with UITableView
• Boilerplate
• Painful when data sources are complex and dynamic
• Not type safe (dequeueReusableCellWithIdentifier etc.)
24
What table view actually needs?
Model ViewModel
UITableViewCell
Deadline ;)
25
<ItemType, CellType>
What if…
Line of code
let row = TableRow<String, MyTableViewCell>(item: "string")
28
Demo
TableKit
Open Source
https://github.com/maxsokolov/TableKit
🚀
TableKit
import TableKit
let clickAction = TableRowAction<String, MyTableViewCell>(.click) { (data) in
}
let row = TableRow<String, MyTableViewCell>(item: "string", actions: [clickAction])
tableDirector += TableSection(rows: [row])
31
Functional programming
The power of declarative approach
let rows: [Row] = strings.map { TableRow<String, MyTableViewCell>(item: $0) }
The view layer is simply
a mapping of our data layer
let rows: [Row] = users
.filter({ $0.active })
.map({ UserViewModel(user: $0) })
.map({ TableRow<UserViewModel, UserTableViewCell>(item: $0) })
Resume
• Currently, SDK/API’s are not generic
• Compiler is not perfect
• Can’t be used with Objective-C
• Compile-time type-safety help to know about potential
issues earlier
• We could build great, flexible, easy to use API’s
35
Links
36
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
TableKit
https://github.com/maxsokolov/TableKit
AvitoTech
https://twitter.com/avitotech
THANK YOU!
QUESTIONS?
Max Sokolov - iOS dev @ Avito
max_sokolov
https://github.com/maxsokolov

More Related Content

PDF
Real World Generics In Swift
PDF
Advanced Swift Generics
PDF
The Ring programming language version 1.3 book - Part 83 of 88
PDF
LetSwift RxSwift 시작하기
PDF
The Ring programming language version 1.2 book - Part 5 of 84
PPTX
Functional Reactive Programming (FRP): Working with RxJS
PPTX
Constructor and destructor
PDF
Functional Core, Reactive Shell
Real World Generics In Swift
Advanced Swift Generics
The Ring programming language version 1.3 book - Part 83 of 88
LetSwift RxSwift 시작하기
The Ring programming language version 1.2 book - Part 5 of 84
Functional Reactive Programming (FRP): Working with RxJS
Constructor and destructor
Functional Core, Reactive Shell

What's hot (20)

PPT
Collection v3
PDF
Hadoop + Clojure
PPT
Oop lec 5-(class objects, constructor & destructor)
PDF
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
PPTX
constructor and destructor
PPT
JavaScript Objects
PPTX
Oct13' ----
TXT
123
PDF
For mobile 5/13'
PPTX
03 standard class library
PDF
JavaScript Foundations Day1
PDF
TypeScript Introduction
PPTX
Constructor ppt
PPTX
Introduction to java 8 stream api
PDF
Manipulating object-behavior-at-runtime
PPTX
ES6 in Real Life
PDF
Introduction aux Macros
PPTX
Mobile TechTalk - Interesting talks from NSConference 6
PDF
Constructor and Destructor
Collection v3
Hadoop + Clojure
Oop lec 5-(class objects, constructor & destructor)
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
constructor and destructor
JavaScript Objects
Oct13' ----
123
For mobile 5/13'
03 standard class library
JavaScript Foundations Day1
TypeScript Introduction
Constructor ppt
Introduction to java 8 stream api
Manipulating object-behavior-at-runtime
ES6 in Real Life
Introduction aux Macros
Mobile TechTalk - Interesting talks from NSConference 6
Constructor and Destructor
Ad

Similar to Adopting Swift Generics (20)

PPTX
Real World Asp.Net WebApi Applications
PPTX
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
PPTX
Mobile Developers Talks: Delve Mobile
PDF
Adopting F# at SBTech
PPTX
Intro to .NET for Government Developers
PPTX
Code camp 2011 Getting Started with IOS, Una Daly
PDF
XAML/C# to HTML/JS
PPTX
Vertical Slicing Architectures
PDF
Iphone lecture imp
PPTX
Umbraco OktoberFest 2014
PPT
Csharp dot net
PDF
Migrating Objective-C to Swift
PDF
.Net Classes and Objects | UiPath Community
PDF
.NET Portfolio
PDF
Enforce Consistentcy with Clean Architecture
PDF
Building modular software with OSGi - Ulf Fildebrandt
PDF
Rider - Taking ReSharper out of Process
PDF
Building Modern Apps using Android Architecture Components
PPT
Silverlight 2 for Developers - TechEd New Zealand 2008
PPTX
Certification preparation - Net classses and functions.pptx
Real World Asp.Net WebApi Applications
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Mobile Developers Talks: Delve Mobile
Adopting F# at SBTech
Intro to .NET for Government Developers
Code camp 2011 Getting Started with IOS, Una Daly
XAML/C# to HTML/JS
Vertical Slicing Architectures
Iphone lecture imp
Umbraco OktoberFest 2014
Csharp dot net
Migrating Objective-C to Swift
.Net Classes and Objects | UiPath Community
.NET Portfolio
Enforce Consistentcy with Clean Architecture
Building modular software with OSGi - Ulf Fildebrandt
Rider - Taking ReSharper out of Process
Building Modern Apps using Android Architecture Components
Silverlight 2 for Developers - TechEd New Zealand 2008
Certification preparation - Net classses and functions.pptx
Ad

Recently uploaded (20)

PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
KodekX | Application Modernization Development
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Network Security Unit 5.pdf for BCA BBA.
NewMind AI Monthly Chronicles - July 2025
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
KodekX | Application Modernization Development
Diabetes mellitus diagnosis method based random forest with bat algorithm
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
The Rise and Fall of 3GPP – Time for a Sabbatical?
Digital-Transformation-Roadmap-for-Companies.pptx
Approach and Philosophy of On baking technology
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Review of recent advances in non-invasive hemoglobin estimation
20250228 LYD VKU AI Blended-Learning.pptx
Spectral efficient network and resource selection model in 5G networks
Reach Out and Touch Someone: Haptics and Empathic Computing
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Adopting Swift Generics