Last active
August 29, 2015 14:23
-
-
Save kasei/aa096c4c2ff8afa2e6b9 to your computer and use it in GitHub Desktop.
Generics handling for protocol return value
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
// In response to: http://inessential.com/2015/06/21/swift_protocols_question | |
import Foundation | |
protocol Value: Equatable { | |
} | |
protocol Smashable { | |
func valueBySmashingOtherValue<T: Value, U: Value>(value: T) -> U | |
} | |
struct Bar : Value { | |
} | |
struct Foo : Value { | |
func valueBySmashingOtherValue<T : Value>(value: T) -> Bar { | |
return Bar() | |
} | |
} | |
func ==(lhs: Bar, rhs: Bar) -> Bool { | |
return true | |
} | |
func ==(lhs: Foo, rhs: Foo) -> Bool { | |
return true | |
} | |
let f = Foo() | |
let b = f.valueBySmashingOtherValue(f) | |
print("bar \(b)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The issue here is that the argument and return value for
valueBySmashing
aren't necessarily the same type. The only constraint here is that both types should conform toValue
. So the function needs to be parameterized with bothT
andU
, both of which are marked as conforming toValue
. That way, the type system can determine thatb
is of typeBar
on line 32, without explicit variable typing.