Skip to content

Instantly share code, notes, and snippets.

@hooman
Last active October 13, 2016 07:56
Show Gist options
  • Save hooman/3d9329d64f8a3cfa877b to your computer and use it in GitHub Desktop.
Save hooman/3d9329d64f8a3cfa877b to your computer and use it in GitHub Desktop.
A sample to demonstrate how to simulate multimethods in Swift
// Simulating multimethods in Swift
// Consider these two hierarchies:
// FamilyA
// / \
// A1 A2
// \
// SubA1
public class FamilyA { }
public class A1: FamilyA { }
public class SubA1: A1 { }
public class A2: FamilyA {}
// FamilyB
// / \
// B1 B2
// \
// SubB1
public class FamilyB { }
public class B1: FamilyB { }
public class SubB1: B1 { }
public class B2: FamilyB {}
public func multimethod( a: FamilyA, b: FamilyB ) {
// Dispatch based on the dynamic type of a and b:
// Be careful about case order: They should be from the most specific to less
// specific and you may have a hard time deciding on some cases.
switch (a, b) {
case let (a as SubA1, b as B1): multimethod(subA1: a, b1: b)
case let (a as A2, b as B1): multimethod(a2: a, b1: b)
case let (a as A2, b as B2): multimethod(a2: a ,b2: b)
default: _multimethod(a,b)
}
}
// Default implementation for the general parameter types:
private func _multimethod(a: FamilyA, b: FamilyB) {
println("Default: a is FamilyA, b is FamilyB")
}
// As you see, there is no point in function overloading here. Selection is done at runtime:
private func multimethod(#subA1: SubA1, #b1: B1) { println("Case: a as SubA1, b as B1") }
private func multimethod(#a2: A2, #b1: B1) { println("Case: a as A2, b as B1") }
private func multimethod(#a2: A2, #b2: B2) { println("Case: a as A2, b as B2") }
// Now lets try it out:
var a1 = A1(), a2 = A2(), a3 = SubA1()
var b1 = B1(), b2 = B2(), b3 = SubB1()
println("1. a is A1, b is B1")
multimethod(a1,b1)
println("2. a is A1, b is B2")
multimethod(a1,b2)
println("3. a is A1, b is SubB1")
multimethod(a1,b3)
println("4. a is A2, b is B1")
multimethod(a2,b1)
println("5. a is A2, b is B2")
multimethod(a2,b2)
println("6. a is A2, b is SubB1")
multimethod(a2,b3)
println("7. a is SubA1, b is B1")
multimethod(a3,b1)
println("8. a is SubA1, b is B2")
multimethod(a3,b2)
println("9. a is SubA1, b is SubB1")
multimethod(a3,b3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment