Skip to content

Instantly share code, notes, and snippets.

@flyinghyrax
Created July 28, 2016 19:15
Show Gist options
  • Save flyinghyrax/d6d9e76de4886d4b62ecdebbae0706ad to your computer and use it in GitHub Desktop.
Save flyinghyrax/d6d9e76de4886d4b62ecdebbae0706ad to your computer and use it in GitHub Desktop.
Goofing off
/// A protocol with an associated type requirement
protocol SomeProtocol {
associatedtype SomePAT
func someFunction(param: SomePAT)
}
/// A generic class which satisfies the associated type with its generic parameter
class Base<T>: SomeProtocol {
func someFunction(param: T) {
print("Executed Base")
}
}
/// A dummy type so we have a concrete type to play with
struct Thing {
let property: Any
}
/// When extending the generic, if we provide a concrete type parameter for the parent
/// then the child does not also have to be generic.
class Child: Base<Thing> {
override func someFunction(param: Thing) {
super.someFunction(param)
print("Executed Child")
}
}
/// A function that uses out PAT as a generic contraint;
/// We can pass an instance of Child to it (though we can't use it for much!)
func example<T: SomeProtocol, U where U == T.SomePAT>(param: T, _ other: U) {
param.someFunction(other)
}
example(Child(), Thing(property: 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment