Skip to content

Instantly share code, notes, and snippets.

@jessesquires
Last active July 6, 2019 02:39
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 jessesquires/ea3aee0c9c7b4d570807e3a7016d7091 to your computer and use it in GitHub Desktop.
Save jessesquires/ea3aee0c9c7b4d570807e3a7016d7091 to your computer and use it in GitHub Desktop.
import Cocoa
protocol Shape { }
struct Triangle: Shape { }
// Function signature requires a concrete type T, it is specialized by T
// Think of it as having a unique function per type:
// - `protoflip(_ s: Triangle) -> Shape`
// - `protoflip(_ s: Square) -> Shape`
// - `protoflip(_ s: Circle) -> Shape`
//
func protoFlip<T: Shape>(_ shape: T) -> Shape {
return shape
}
let triangle = Triangle()
// Error: protocol type 'Shape' cannot conform to 'Shape'
// because only concrete types can conform to protocols
// Does not work because you receive T but return Shape
// T is more specific than Shape
// Think: subclass vs superclass
protoFlip(protoFlip(triangle))
// ------------------------
// Function does not require a concrete type
func protoFlip2(_ shape: Shape) -> Shape {
return shape
}
// Works
// function receives and returns Shape
protoFlip2(protoFlip2(triangle))
// This would also work, because you return a specific T
func protoFlip3<T: Shape>(_ shape: T) -> T {
return shape
}
// Works
// function receives and returns T
// in this case T = Triangle
protoFlip3(protoFlip3(triangle))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment