Slide 1

Slide 1 text

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

Slide 2

Slide 2 text

Mercari / Souzoh iOS / Swift Engineer / @orakaro

Slide 3

Slide 3 text

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

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

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

Slide 8

Slide 8 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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 defined type in Swift is Invariance Custom type

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

Recap

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

Twitter / Github: @orakaro Thank you