SlideShare a Scribd company logo
Protocols and generics in Swift
- Facilitate polymorphism 

- Share common behaviors and properties

- Provide contract between architecture layers

- Allow decoupling components 

- Help to improve testability
Protocols
/// Generic constraints, type-level
/// abstraction
func foo<T: Equatable>(x: T, y: T) {
print(x == y)
}
/// Static dispatch
foo(x: 10, y: 100)
/// Existential types, value-level
/// abstraction
let x: CustomStringConvertible = 100
let y: CustomStringConvertible = "My string"
var z = y
z = UIColor.red
func foo(x: CustomStringConvertible,
y: CustomStringConvertible) {
print("(x.description) (y.description)")
}
/// Dynamic dispatch
foo(x: 100, y: “My string”)
func foo(x: Equatable, y: Equatable) {
print(x == y)
/// Protocol 'Equatable' can only be used
/// as a generic constraint because it has
/// Self or associated type requirements
}
protocol P {
/// Customization point
/// Dynamic dispatch
func foo()
}
extension P {
func foo() { print("Extension foo") }
/// Static dispatch
/// No polymorphism
func bar() { print("Extension bar") }
}
struct S: P {
func foo() { print("Struct foo") }
func bar() { print("Struct bar") }
}
let s = S()
s.foo() // Struct foo
s.bar() // Struct bar
let p: P = S()
p.foo() // Struct foo
p.bar() // Extension bar
- Avoid code duplication

- Abstract algorithms

- Improve type safety 

- Make code more readable
Generics
struct Stack<T> {
/// ...
}
final class Repository<Entity: Codable> {
/// ...
}
protocol IteratorProtocol {
associatedtype Element
mutating func next() -> Element?
}
let it: IteratorProtocol = /// ...
it.next()
Generalized existential
protocol ConvertibeToValue<T> {
func convert() -> T
}
extension Entity: ConvertibeToValue<ViewModel1> {
func convert() -> ViewModel1
}
extension Entity: ConvertibeToValue<ViewModel2> {
func convert() -> ViewModel2
}
Will never be implemented
protocol Convertible {
associatedtype ToValue
func conver() -> ToValue
}
extension Entity: Convertible {
typealias ToValue = ViewModel1
func conver() -> ViewModel1 {}
}
extension Entity: Convertible {
typealias ToValue = ViewModel2
func conver() -> ViewModel2 {
/// Redundant conformance of 'Entity'
/// to protocol 'Convertibe'
}
}
Thank you!

More Related Content

PDF
Swift 3.0 の新しい機能(のうちの9つ)
PDF
AnyObject – 自分が見落としていた、基本の話
PDF
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
PDF
Javascript & Ajax Basics
PPT
FSE 2008
PDF
Haxe: What Makes It Cool
PDF
MP in Clojure
PDF
The best of AltJava is Xtend
Swift 3.0 の新しい機能(のうちの9つ)
AnyObject – 自分が見落としていた、基本の話
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Javascript & Ajax Basics
FSE 2008
Haxe: What Makes It Cool
MP in Clojure
The best of AltJava is Xtend

What's hot (19)

DOCX
Oops pramming with examples
PPT
Java Script Introduction
TXT
Source Code
PDF
Composite types
PDF
Generics and Inference
PPTX
C++ hello world
PDF
ECMAScript 6 and beyond
PPT
Oop lecture9 12
PPT
Lecture 12 - Recursion
PPTX
03loop conditional statements
PDF
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
PPTX
Introduction to c
PDF
Swiftの関数型っぽい部分
PPT
Perl Intro 4 Debugger
PDF
Pointers & functions
PPTX
Introduction to Perl Programming
PDF
c programming
PDF
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
PDF
Back to the Future with TypeScript
Oops pramming with examples
Java Script Introduction
Source Code
Composite types
Generics and Inference
C++ hello world
ECMAScript 6 and beyond
Oop lecture9 12
Lecture 12 - Recursion
03loop conditional statements
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
Introduction to c
Swiftの関数型っぽい部分
Perl Intro 4 Debugger
Pointers & functions
Introduction to Perl Programming
c programming
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Back to the Future with TypeScript
Ad

Similar to Protocols and generics in Swift (20)

KEY
Beauty and Power of Go
PDF
Thumbtack Expertise Days # 5 - Javaz
PDF
Application Integration with XProc
PDF
The Swift Compiler and Standard Library
PDF
So various polymorphism in Scala
PDF
Javaz. Functional design in Java 8.
PDF
Ti1220 Lecture 2: Names, Bindings, and Scopes
PDF
Introduction to the rust programming language
PDF
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
PDF
All About ... Functions
PDF
Web 4 | Core JavaScript
PDF
Kotlin Delegates: Reduce the boilerplate
PDF
FP in Java - Project Lambda and beyond
PPTX
Introduction of flex
PDF
Whats to come with swift generics
PDF
deepjs - tools for better programming
PDF
Demystifying Type Class derivation with Shapeless
PDF
Humble introduction to category theory in haskell
PPTX
LISP:Declarations In Lisp
Beauty and Power of Go
Thumbtack Expertise Days # 5 - Javaz
Application Integration with XProc
The Swift Compiler and Standard Library
So various polymorphism in Scala
Javaz. Functional design in Java 8.
Ti1220 Lecture 2: Names, Bindings, and Scopes
Introduction to the rust programming language
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
All About ... Functions
Web 4 | Core JavaScript
Kotlin Delegates: Reduce the boilerplate
FP in Java - Project Lambda and beyond
Introduction of flex
Whats to come with swift generics
deepjs - tools for better programming
Demystifying Type Class derivation with Shapeless
Humble introduction to category theory in haskell
LISP:Declarations In Lisp
Ad

More from Andrey Volobuev (9)

PDF
Prompt engineering for iOS developers (How LLMs and GenAI work)
PDF
State machines in iOS
PDF
Mobile architectures
PDF
Functional
PDF
How React works
PDF
Unit testing iOS Applications
PDF
Архитектура компилятора Swift
PDF
Преимущества и недостатки языка Swift
Prompt engineering for iOS developers (How LLMs and GenAI work)
State machines in iOS
Mobile architectures
Functional
How React works
Unit testing iOS Applications
Архитектура компилятора Swift
Преимущества и недостатки языка Swift

Recently uploaded (20)

PDF
MCP Security Tutorial - Beginner to Advanced
PDF
Types of Token_ From Utility to Security.pdf
PPTX
Computer Software and OS of computer science of grade 11.pptx
PPTX
Tech Workshop Escape Room Tech Workshop
PPTX
Oracle Fusion HCM Cloud Demo for Beginners
PDF
Salesforce Agentforce AI Implementation.pdf
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
Introduction to Windows Operating System
PPTX
Weekly report ppt - harsh dattuprasad patel.pptx
PDF
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
PDF
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
PPTX
chapter 5 systemdesign2008.pptx for cimputer science students
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PDF
Designing Intelligence for the Shop Floor.pdf
PDF
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
DOCX
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
PDF
STL Containers in C++ : Sequence Container : Vector
PPTX
Advanced SystemCare Ultimate Crack + Portable (2025)
PDF
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
PDF
AI/ML Infra Meetup | LLM Agents and Implementation Challenges
MCP Security Tutorial - Beginner to Advanced
Types of Token_ From Utility to Security.pdf
Computer Software and OS of computer science of grade 11.pptx
Tech Workshop Escape Room Tech Workshop
Oracle Fusion HCM Cloud Demo for Beginners
Salesforce Agentforce AI Implementation.pdf
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Introduction to Windows Operating System
Weekly report ppt - harsh dattuprasad patel.pptx
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
chapter 5 systemdesign2008.pptx for cimputer science students
Why Generative AI is the Future of Content, Code & Creativity?
Designing Intelligence for the Shop Floor.pdf
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
STL Containers in C++ : Sequence Container : Vector
Advanced SystemCare Ultimate Crack + Portable (2025)
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
AI/ML Infra Meetup | LLM Agents and Implementation Challenges

Protocols and generics in Swift

  • 2. - Facilitate polymorphism - Share common behaviors and properties - Provide contract between architecture layers - Allow decoupling components - Help to improve testability Protocols
  • 3. /// Generic constraints, type-level /// abstraction func foo<T: Equatable>(x: T, y: T) { print(x == y) } /// Static dispatch foo(x: 10, y: 100)
  • 4. /// Existential types, value-level /// abstraction let x: CustomStringConvertible = 100 let y: CustomStringConvertible = "My string" var z = y z = UIColor.red
  • 5. func foo(x: CustomStringConvertible, y: CustomStringConvertible) { print("(x.description) (y.description)") } /// Dynamic dispatch foo(x: 100, y: “My string”)
  • 6. func foo(x: Equatable, y: Equatable) { print(x == y) /// Protocol 'Equatable' can only be used /// as a generic constraint because it has /// Self or associated type requirements }
  • 7. protocol P { /// Customization point /// Dynamic dispatch func foo() } extension P { func foo() { print("Extension foo") } /// Static dispatch /// No polymorphism func bar() { print("Extension bar") } }
  • 8. struct S: P { func foo() { print("Struct foo") } func bar() { print("Struct bar") } } let s = S() s.foo() // Struct foo s.bar() // Struct bar let p: P = S() p.foo() // Struct foo p.bar() // Extension bar
  • 9. - Avoid code duplication - Abstract algorithms - Improve type safety - Make code more readable Generics
  • 10. struct Stack<T> { /// ... } final class Repository<Entity: Codable> { /// ... }
  • 11. protocol IteratorProtocol { associatedtype Element mutating func next() -> Element? } let it: IteratorProtocol = /// ... it.next() Generalized existential
  • 12. protocol ConvertibeToValue<T> { func convert() -> T } extension Entity: ConvertibeToValue<ViewModel1> { func convert() -> ViewModel1 } extension Entity: ConvertibeToValue<ViewModel2> { func convert() -> ViewModel2 } Will never be implemented
  • 13. protocol Convertible { associatedtype ToValue func conver() -> ToValue } extension Entity: Convertible { typealias ToValue = ViewModel1 func conver() -> ViewModel1 {} } extension Entity: Convertible { typealias ToValue = ViewModel2 func conver() -> ViewModel2 { /// Redundant conformance of 'Entity' /// to protocol 'Convertibe' } }