Skip to content

Instantly share code, notes, and snippets.

@rnapier
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rnapier/7321b964497cbc779b7b to your computer and use it in GitHub Desktop.
Save rnapier/7321b964497cbc779b7b to your computer and use it in GitHub Desktop.
Generics do not compose (is that the right way to think about it?)
// Generics do not compose
// The generic f()
func f<T>(x: T) -> T { return g(x) }
// The every-day g() that f() calls
func g<T>(x: T) -> T {
return x
}
// A special thing that some types can do
protocol Doubleable {
func double() -> Self
}
// String is one of those types
extension String : Doubleable {
func double() -> String {
return self + self
}
}
// And a special g() for types that can do that special thing
func g<T:Doubleable>(x: T) -> T {
return x.double()
}
// Let's see what we call
f(1) // => 1
f([1]) // => [1]
g("this") // => "thisthis" (Here, we specialize to the Doubleable g())
f("this") // => "this" (should be "thisthis", since String is Doubleable)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment