SlideShare a Scribd company logo
Protocols with
Associated Types
and how they got that way
(maybe)
 
@alexisgallagher
Protocols with Associated Pain
1. Hurray, I'm using value types!
2. Oh, I can't subclass.
3. Hurray, I'm using protocols!
4. Hurray, I'm adopting Equatable!
5.
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Pain
Plain protocols, work as expected:
protocol MyProto {
}
struct Foo : MyProto {
}
let protoVar:MyProto = Foo() // <-- No problem!
Protocols with Associated Pain
Protocols with associated types, do not:
protocol MyProto {
typealias MyAssocType // declare requirement
}
struct Foo : MyProto {
typealias MyAssocType = Int // meet requirement
}
let protoVar:MyProto = Foo() // <-- Nope!
Protocols with Associated Pain
Protocols requiring Self? Same story:
protocol MyEquatable {
typealias MySelf // Self is a special associated type ...
}
struct Foo : MyEquatable {
typealias MySelf = Foo // ... always equal to adopting type
}
let protoVar:MyEquatable = Foo() // <-- Nope!
PATs are a bit weird
why ?
Comprendre c'est
pardonner
Questions
1. How are PATs weird?
2. Why are PATs weird?
3. Is this the plan?
4. How to love them?
How PATs are weird
W1. Only usable as generic constraints
Weirdness 1: only usable as generic constraints
• This rule excludes PATs from literally every single use of
"protocols" as defined in Objective-C
Weirdness 1: only usable as generic constraints
• This rule excludes PATs from literally every single use of
"protocols" as defined in Objective-C
• Everywhere you wanted a protocol, you need a generic:
   From:   var delegate:Proto
   To:        class C<T:Proto> { var delegate:T } }
Weirdness 1: only usable as generic constraints
• This rule excludes PATs from literally every single use of
"protocols" as defined in Objective-C
• Everywhere you wanted a protocol, you need a generic:
   From:   var delegates:[Proto]
   To:        class C<T:Proto> { var delegates:[T] } }
• Which still excludes dynamic dispatch … which might be
why you wanted a protocol to begin with!
How PATs are weird
W2. Docs describe them as "real" types
Protocols with Associated Types, and How They Got That Way
How PATs are weird
W3. The mysterious typealias
Weirdness 3: the mysterious typealias
typealias serves two different functions:
1. Outside PATs: provides the syntactic convenience of
meaningful names
2. Inside PATs, establishes a semantic requirement on types
adopting the PAT
Weirdness 3: the mysterious typealias
• typealias defines a placeholder for an unknown type ...
• ... which can be used throughout the protocol definition
protocol Animal {
typealias Food
func eat(food:Food) { }
}
This sounds familiar...
Weirdness 3: the mysterious typealias
typealias feels like a generic type parameter!
struct Animal<Food> {
func eat(food:Food) { }
}
protocol Animal {
typealias Food
func eat(food:Food) { }
}
Are PATs just generic protocols
with whacky syntax??
Does that explain everything?!
No
No
And yes, sort of
2. Why PATs are weird
The problem associated types solve
Subtyping alone cannot capture rich type relations
protocol Food { }
struct Grass : Food { }
protocol Animal {
func eat(f:Food)
}
struct Cow : Animal {
func eat(f:Grass) { } // <- error, Cow must eat Food
}
The problem associated types solve
Subtyping alone cannot capture rich type relations
protocol Food { }
struct Grass : Food { }
protocol Animal {
typealias Food
func eat(f:Food)
}
struct Cow { }
extension Cow : Animal {
func eat(f:Food) { } // <- OK
}
But why not use generic protocol syntax?
/// imaginary generic protocol swift
protocol Animal<Food> {
func eat(food:Food)
}
extension Cow : Animal<Grass> {
func eat(f:Grass) { }
}
But why not use generic protocol syntax?
• Because from outside the protocol, consumers could only
see the associated type by parameterizing over it:
/// generic-protocol-swift
func feedAnimal<A:Animal<F>,F>(a:A) {
// I see an F, and oh yeah F is a type variable for food
}
• But Swift PATs provide direct named access to associated
type, like properties
func feedAnimal<A:Animal>(a:A) {
// I see the assoc type: A.Food
}
But why not use generic protocol syntax?
And this problem compounds when protocols:
• have many associated types
• which might themselves be constrained by protocols
• and we want to use them all at once
Generic Graph BFS in Java (v 1.3)
public class breadth_first_search {
public static <
GraphT extends VertexListGraph<Vertex, VertexIterator, ?> &
IncidenceGraph<Vertex, Edge, OutEdgeIterator, ?>,
Vertex,
Edge extends GraphEdge<Vertex>,
VertexIterator extends Collection<Vertex>,
OutEdgeIterator extends Collection<Edge>,
ColorMap extends ReadWritePropertyMap<Vertex, ColorValue>,
Visitor extends BFSVisitor<GraphT, Vertex, Edge>>
void go(GraphT g, Vertex s, ColorMap c, Visitor vis);
}
Generic Graph BFS in C++
template <class G, class C, class Vis>
void breadth_first_search(const G& g,
typename graph traits<G>::vertex s, C c, Vis vis);
// constraints:
// G models Vertex List Graph and Incidence Graph
// C models Read/Write Map
// map traits<C>::key == graph traits<G>::vertex
// map traits<C>::value models Color
// Vis models BFS Visitor
Generic Graph BFS in Haskell (Hugs 2002)
breadth_first_search ::
(VertexListGraph g v, IncidenceGraph g e v,
ReadWriteMap c v Color, BFSVisitor vis a g e v) =>
g ! v ! c ! vis ! a ! a
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
3. Is this the plan?
Yes*
Two Worlds of Protocols
Without Self Requirement With Self Requirement
func precedes(other: Ordered) -> Bool func precedes(other: Self) -> Bool
Usable as a type
func sort(inout a: [Ordered])
Only usable as a generic constraint
func sort<T : Ordered>(inout a: [T])
Think“heterogeneous” Think“homogeneous”
Every model must deal with all others Models are free from interaction
Dynamic dispatch Static dispatch
Less optimizable More optimizable
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
* Existentials?
Protocols with Associated Types, and How They Got That Way
Comprendre c'est
pardonner
Questions
1. How are PATs weird?
2. Why are PATs weird?
3. Is this the plan?
4. How to love them?
Answers
How PATs are weird
• Lock you into generics and static dispatch
• typealias syntax plays two roles
• Associated type is as much like a required property as like a
type parameter
Answers
Why PATs are weird
• Rich, multi-type abstractions do not "fit" in OOP subtyping
• Designed to address known issues with naive "generic
protocol" designs (complexity scales badly with more
associated types)
Answers
Yes, functioning as planned
• Seems informed by C++ concepts, Haskell type classes, SML
signatures, generics in C# and Java, abstract type members
in Scala, etc.
• Impact on OOP "protocol" pattern: collateral damage
• Existentials?
4. How to love them?
Call them
PATs
Answers
How to love them
• Call them PATs
• Embrace generics
• If you still need dynamic dispatch
• use enums to push runtime variation into values
• use type erasure to hide dynamic dispatch within a type
• wait for existentials?
Protocols with
Associated Types
and how they got that way
(but now we can just ask on swift-evolution, right?)
 
@alexisgallagher

More Related Content

PPTX
Python programming
PDF
The Swift Compiler and Standard Library
PPSX
Programming with Python
PPTX
Python The basics
PPTX
Java New Programming Features
PPTX
Learn Python The Hard Way Presentation
PPTX
PPT
02basics
Python programming
The Swift Compiler and Standard Library
Programming with Python
Python The basics
Java New Programming Features
Learn Python The Hard Way Presentation
02basics

What's hot (20)

PDF
Denis Lebedev, Swift
PPTX
Functions, List and String methods
PPSX
DITEC - Programming with Java
PPTX
FUNDAMENTALS OF PYTHON LANGUAGE
PPSX
String and string manipulation x
PDF
1 kotlin vs. java: some java issues addressed in kotlin
PPTX
Python language data types
PPTX
Java vs kotlin
PPTX
Python ppt
PDF
Python
PDF
Python in 90 minutes
PDF
Python for data science by www.dmdiploma.com
PDF
Python idiomatico
PDF
Os Goodger
PPT
python.ppt
PPSX
DISE - Windows Based Application Development in Java
PDF
Swift Introduction
PPT
Introduction to Python - Part Two
PPT
The JavaScript Programming Language
PPT
The Java Script Programming Language
Denis Lebedev, Swift
Functions, List and String methods
DITEC - Programming with Java
FUNDAMENTALS OF PYTHON LANGUAGE
String and string manipulation x
1 kotlin vs. java: some java issues addressed in kotlin
Python language data types
Java vs kotlin
Python ppt
Python
Python in 90 minutes
Python for data science by www.dmdiploma.com
Python idiomatico
Os Goodger
python.ppt
DISE - Windows Based Application Development in Java
Swift Introduction
Introduction to Python - Part Two
The JavaScript Programming Language
The Java Script Programming Language
Ad

Viewers also liked (15)

PDF
Swift, functional programming, and the future of Objective-C
PDF
Open Lecture Peter Hilbers - July 8, 2016
PDF
Data Sheet: Why Your eCommerce Platform Needs CIAM
PDF
How to Build a Strategic Talent Pipeline
PPT
COM 110: Chapter 1
PPTX
Onderwijs voor iedereen met Khan Academy
PDF
Unity歴0秒は何故ゲームジャムに飛び込んだのか
PDF
Foodborne Illnesses 101
PDF
AJC 2011 Presentation - Building a Successful Marketing Strategy and Budget
PPTX
Links as Language: A Contextual Approach to Content Creation
PDF
Programma Nazionale per la Ricerca
PDF
PR for CEO's: strategy and tips
PPTX
How PR Communicators Can Stay Relevant
PDF
Guide to EV SSL certificate enrollment - by Comodo
Swift, functional programming, and the future of Objective-C
Open Lecture Peter Hilbers - July 8, 2016
Data Sheet: Why Your eCommerce Platform Needs CIAM
How to Build a Strategic Talent Pipeline
COM 110: Chapter 1
Onderwijs voor iedereen met Khan Academy
Unity歴0秒は何故ゲームジャムに飛び込んだのか
Foodborne Illnesses 101
AJC 2011 Presentation - Building a Successful Marketing Strategy and Budget
Links as Language: A Contextual Approach to Content Creation
Programma Nazionale per la Ricerca
PR for CEO's: strategy and tips
How PR Communicators Can Stay Relevant
Guide to EV SSL certificate enrollment - by Comodo
Ad

Similar to Protocols with Associated Types, and How They Got That Way (20)

PPTX
Protocol oriented programming_talk_ppt
PDF
Protocols with Associated Types
PDF
A glimpse into protocols with associated type and type erasure
PDF
Protocols and generics in Swift
PDF
dotSwift 2016 : Beyond Crusty - Real-World Protocols
PPTX
Swift Generics
PDF
Generics With Swift
PDF
Protocol in Swift
PDF
Generics programming in Swift
PDF
Swift Generics in Theory and Practice
PPTX
Protocol-Oriented Programming in Swift
PDF
Swift cooking course making a cake ... pattern
PDF
Infinum iOS Talks #1 - Swift done right by Ivan Dikic
PDF
Cocoaheads Meetup / Alex Zimin / Swift magic
PDF
Александр Зимин (Alexander Zimin) — Магия Swift
PDF
Building reusable components with generics and protocols
PDF
Whats to come with swift generics
PDF
Protocol-Oriented Programming in Swift
PDF
Gunosy.go#7 reflect
PDF
Swift 2
Protocol oriented programming_talk_ppt
Protocols with Associated Types
A glimpse into protocols with associated type and type erasure
Protocols and generics in Swift
dotSwift 2016 : Beyond Crusty - Real-World Protocols
Swift Generics
Generics With Swift
Protocol in Swift
Generics programming in Swift
Swift Generics in Theory and Practice
Protocol-Oriented Programming in Swift
Swift cooking course making a cake ... pattern
Infinum iOS Talks #1 - Swift done right by Ivan Dikic
Cocoaheads Meetup / Alex Zimin / Swift magic
Александр Зимин (Alexander Zimin) — Магия Swift
Building reusable components with generics and protocols
Whats to come with swift generics
Protocol-Oriented Programming in Swift
Gunosy.go#7 reflect
Swift 2

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
KodekX | Application Modernization Development
PPTX
Spectroscopy.pptx food analysis technology
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Big Data Technologies - Introduction.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
sap open course for s4hana steps from ECC to s4
Teaching material agriculture food technology
“AI and Expert System Decision Support & Business Intelligence Systems”
The Rise and Fall of 3GPP – Time for a Sabbatical?
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Mobile App Security Testing_ A Comprehensive Guide.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
KodekX | Application Modernization Development
Spectroscopy.pptx food analysis technology
20250228 LYD VKU AI Blended-Learning.pptx
Review of recent advances in non-invasive hemoglobin estimation
Big Data Technologies - Introduction.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Advanced methodologies resolving dimensionality complications for autism neur...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Dropbox Q2 2025 Financial Results & Investor Presentation
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
MIND Revenue Release Quarter 2 2025 Press Release
sap open course for s4hana steps from ECC to s4

Protocols with Associated Types, and How They Got That Way

  • 1. Protocols with Associated Types and how they got that way (maybe)   @alexisgallagher
  • 2. Protocols with Associated Pain 1. Hurray, I'm using value types! 2. Oh, I can't subclass. 3. Hurray, I'm using protocols! 4. Hurray, I'm adopting Equatable! 5.
  • 4. Protocols with Associated Pain Plain protocols, work as expected: protocol MyProto { } struct Foo : MyProto { } let protoVar:MyProto = Foo() // <-- No problem!
  • 5. Protocols with Associated Pain Protocols with associated types, do not: protocol MyProto { typealias MyAssocType // declare requirement } struct Foo : MyProto { typealias MyAssocType = Int // meet requirement } let protoVar:MyProto = Foo() // <-- Nope!
  • 6. Protocols with Associated Pain Protocols requiring Self? Same story: protocol MyEquatable { typealias MySelf // Self is a special associated type ... } struct Foo : MyEquatable { typealias MySelf = Foo // ... always equal to adopting type } let protoVar:MyEquatable = Foo() // <-- Nope!
  • 7. PATs are a bit weird why ?
  • 9. Questions 1. How are PATs weird? 2. Why are PATs weird? 3. Is this the plan? 4. How to love them?
  • 10. How PATs are weird W1. Only usable as generic constraints
  • 11. Weirdness 1: only usable as generic constraints • This rule excludes PATs from literally every single use of "protocols" as defined in Objective-C
  • 12. Weirdness 1: only usable as generic constraints • This rule excludes PATs from literally every single use of "protocols" as defined in Objective-C • Everywhere you wanted a protocol, you need a generic:    From:   var delegate:Proto    To:        class C<T:Proto> { var delegate:T } }
  • 13. Weirdness 1: only usable as generic constraints • This rule excludes PATs from literally every single use of "protocols" as defined in Objective-C • Everywhere you wanted a protocol, you need a generic:    From:   var delegates:[Proto]    To:        class C<T:Proto> { var delegates:[T] } } • Which still excludes dynamic dispatch … which might be why you wanted a protocol to begin with!
  • 14. How PATs are weird W2. Docs describe them as "real" types
  • 16. How PATs are weird W3. The mysterious typealias
  • 17. Weirdness 3: the mysterious typealias typealias serves two different functions: 1. Outside PATs: provides the syntactic convenience of meaningful names 2. Inside PATs, establishes a semantic requirement on types adopting the PAT
  • 18. Weirdness 3: the mysterious typealias • typealias defines a placeholder for an unknown type ... • ... which can be used throughout the protocol definition protocol Animal { typealias Food func eat(food:Food) { } } This sounds familiar...
  • 19. Weirdness 3: the mysterious typealias typealias feels like a generic type parameter! struct Animal<Food> { func eat(food:Food) { } } protocol Animal { typealias Food func eat(food:Food) { } }
  • 20. Are PATs just generic protocols with whacky syntax?? Does that explain everything?!
  • 21. No
  • 23. 2. Why PATs are weird
  • 24. The problem associated types solve Subtyping alone cannot capture rich type relations protocol Food { } struct Grass : Food { } protocol Animal { func eat(f:Food) } struct Cow : Animal { func eat(f:Grass) { } // <- error, Cow must eat Food }
  • 25. The problem associated types solve Subtyping alone cannot capture rich type relations protocol Food { } struct Grass : Food { } protocol Animal { typealias Food func eat(f:Food) } struct Cow { } extension Cow : Animal { func eat(f:Food) { } // <- OK }
  • 26. But why not use generic protocol syntax? /// imaginary generic protocol swift protocol Animal<Food> { func eat(food:Food) } extension Cow : Animal<Grass> { func eat(f:Grass) { } }
  • 27. But why not use generic protocol syntax? • Because from outside the protocol, consumers could only see the associated type by parameterizing over it: /// generic-protocol-swift func feedAnimal<A:Animal<F>,F>(a:A) { // I see an F, and oh yeah F is a type variable for food } • But Swift PATs provide direct named access to associated type, like properties func feedAnimal<A:Animal>(a:A) { // I see the assoc type: A.Food }
  • 28. But why not use generic protocol syntax? And this problem compounds when protocols: • have many associated types • which might themselves be constrained by protocols • and we want to use them all at once
  • 29. Generic Graph BFS in Java (v 1.3) public class breadth_first_search { public static < GraphT extends VertexListGraph<Vertex, VertexIterator, ?> & IncidenceGraph<Vertex, Edge, OutEdgeIterator, ?>, Vertex, Edge extends GraphEdge<Vertex>, VertexIterator extends Collection<Vertex>, OutEdgeIterator extends Collection<Edge>, ColorMap extends ReadWritePropertyMap<Vertex, ColorValue>, Visitor extends BFSVisitor<GraphT, Vertex, Edge>> void go(GraphT g, Vertex s, ColorMap c, Visitor vis); }
  • 30. Generic Graph BFS in C++ template <class G, class C, class Vis> void breadth_first_search(const G& g, typename graph traits<G>::vertex s, C c, Vis vis); // constraints: // G models Vertex List Graph and Incidence Graph // C models Read/Write Map // map traits<C>::key == graph traits<G>::vertex // map traits<C>::value models Color // Vis models BFS Visitor
  • 31. Generic Graph BFS in Haskell (Hugs 2002) breadth_first_search :: (VertexListGraph g v, IncidenceGraph g e v, ReadWriteMap c v Color, BFSVisitor vis a g e v) => g ! v ! c ! vis ! a ! a
  • 38. 3. Is this the plan? Yes*
  • 39. Two Worlds of Protocols Without Self Requirement With Self Requirement func precedes(other: Ordered) -> Bool func precedes(other: Self) -> Bool Usable as a type func sort(inout a: [Ordered]) Only usable as a generic constraint func sort<T : Ordered>(inout a: [T]) Think“heterogeneous” Think“homogeneous” Every model must deal with all others Models are free from interaction Dynamic dispatch Static dispatch Less optimizable More optimizable
  • 45. Questions 1. How are PATs weird? 2. Why are PATs weird? 3. Is this the plan? 4. How to love them?
  • 46. Answers How PATs are weird • Lock you into generics and static dispatch • typealias syntax plays two roles • Associated type is as much like a required property as like a type parameter
  • 47. Answers Why PATs are weird • Rich, multi-type abstractions do not "fit" in OOP subtyping • Designed to address known issues with naive "generic protocol" designs (complexity scales badly with more associated types)
  • 48. Answers Yes, functioning as planned • Seems informed by C++ concepts, Haskell type classes, SML signatures, generics in C# and Java, abstract type members in Scala, etc. • Impact on OOP "protocol" pattern: collateral damage • Existentials?
  • 49. 4. How to love them?
  • 51. Answers How to love them • Call them PATs • Embrace generics • If you still need dynamic dispatch • use enums to push runtime variation into values • use type erasure to hide dynamic dispatch within a type • wait for existentials?
  • 52. Protocols with Associated Types and how they got that way (but now we can just ask on swift-evolution, right?)   @alexisgallagher