Orakaro
February 28, 2018
1k

# The diamond of Variances

try! Swift Tokyo 2018 presentation.
https://www.tryswift.co/events/2018/tokyo/en/#diamond

## Orakaro

February 28, 2018

## Transcript

1. Diamond of Variances
Vu Nhat Minh / @orakaro
try! Swift Tokyo 2018

2. Mercari / Souzoh
iOS / Swift Engineer / @orakaro

3. What is Variance ?
Subtyping relationship between type constructor
Which relation of A and B make F a subtype of F ?

4. Contravariance Covariance
Invariance
Phantom Variance
A: B then F : F A: B then F : F
A: B but no relation between F and F
No relation between A and B but F : F
If A is a subtype of B,
then F is a subtype of F

5. Swift Covariance: Array
class Saiyan{}
class SuperSaiyan: Saiyan{}
let goku: Saiyan = SuperSaiyan()
let saiyanArmy: [Saiyan] = [SuperSaiyan]()
A: B
[A] : [B]

6. Swift Covariance: Optional
class Saiyan{}
class SuperSaiyan: Saiyan{}
let gohan: SuperSaiyan? = SuperSaiyan()
let sonOfGoku: Saiyan? = gohan
A: B
A? : B?

7. Contravariance Covariance
Invariance
Phantom Variance
A: B then F : F A: B then F : F
A: B but no relation between F and F
No relation between A and B but F : F
If A is a subtype of B,
then F is a subtype of F

8. Swift Contravariance: Function Parameter
class Saiyan{}
class SuperSaiyan: Saiyan{}
typealias Transform = (T) -> GreatApe
let transformation: Transform = { _ in GreatApe() }
let superTransformation: Transform = transformation
A: B
F : F

9. Contravariance Covariance
A: B then F : F A: B then F : F
Covariance vs Contravariance
typealias Transform1 = (T) -> Void // Contravariance
typealias Transform2 = ((T) -> Void) -> Void // Covariance
typealias Transform3 = (((T) -> Void) -> Void) -> Void // Contravariance
vs

10. Contravariance Covariance
Invariance
Phantom Variance
A: B then F : F A: B then F : F
A: B but no relation between F and F
No relation between A and B but F : F

11. Swift Invariance
protocol Saiyan{}
protocol SuperSaiyan: Saiyan{}
class ZFighter {}
let goku: ZFighter = ZFighter()
let gokuSuperSaiyan: ZFighter = goku ❌
// cannot convert value of type 'ZFighter' to specified type
'ZFighter'
Any custom deﬁned type in Swift is Invariance
Custom type

12. Contravariance Covariance
Invariance
Phantom Variance
A: B then F : F A: B then F : F
A: B but no relation between F and F
No relation between A and B but F : F

13. Phantom Variance
protocol Saiyan {}
protocol Namekian {}
typealias ZFighter<> = Void
let fighter: ZFighter = ZFighter()
A and B have no relation
F : F

14. Recap

15. Contravariance Covariance
Invariance
Phantom Variance
A: B then F : F A: B then F : F
A: B but no relation between F and F
No relation between A and B but F : F

16. Type of Variance
• Covariance : Array and Optional
• Contravariance : Function/Closure parameter
• Invariance : Every Custom Type
• Phantom Variance : Type parameter which is not used inside