Skip to content

Instantly share code, notes, and snippets.

@jkereako
Created February 28, 2018 16:37
Show Gist options
  • Save jkereako/954a1ed1f1bcab31b408518132e5f8a9 to your computer and use it in GitHub Desktop.
Save jkereako/954a1ed1f1bcab31b408518132e5f8a9 to your computer and use it in GitHub Desktop.
Difference between Generic parameter with a type constraint and just a regular type constraint
import Foundation
import PlaygroundSupport
protocol SomeProtocol {
var someProperty: Int { get }
}
// The parameter `some` is of type T and type T conforms to SomeProtocol
func generic<T: SomeProtocol>(some: T) -> Int {
return some.someProperty
}
// The parameter `some` conforms to SomeProtocol
func nonGeneric(some: SomeProtocol) -> Int {
return some.someProperty
}
struct Foo: SomeProtocol {
var someProperty: Int
}
let foo: SomeProtocol = Foo(someProperty: 42)
// This doesn't compile because the `generic(some:)` expects a type T which
// conforms to the protocol SomeProtocol. However, SomeProtocol does not conform
// to itself. generic(some: something)
generic(some: foo)
// This compiles because `foo` conforms to SomeProtocol
nonGeneric(some: foo)
@jkereako
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment