Skip to content

Instantly share code, notes, and snippets.

@kasei
Last active August 29, 2015 14:23
Show Gist options
  • Save kasei/aa096c4c2ff8afa2e6b9 to your computer and use it in GitHub Desktop.
Save kasei/aa096c4c2ff8afa2e6b9 to your computer and use it in GitHub Desktop.
Generics handling for protocol return value
// In response to: http://inessential.com/2015/06/21/swift_protocols_question
import Foundation
protocol Value: Equatable {
}
protocol Smashable {
func valueBySmashing​OtherValue​<T: Value, U: Value>(value: T) -> U
}
struct Bar : Value {
}
struct Foo : Value {
func valueBySmashing​OtherValue​<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.valueBySmashing​OtherValue​(f)
print("bar \(b)")
@kasei
Copy link
Author

kasei commented Jun 21, 2015

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 to Value. So the function needs to be parameterized with both T and U, both of which are marked as conforming to Value. That way, the type system can determine that b is of type Bar on line 32, without explicit variable typing.

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