Created
February 28, 2018 16:37
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credit
What is the in-practice difference between generic and protocol-typed function parameters?