Last active
August 29, 2015 14:07
-
-
Save airspeedswift/a40d9e70f813863ab324 to your computer and use it in GitHub Desktop.
Swift for…in generic inference prob
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
// original version with problem | |
struct A<T> { | |
func f<S: SequenceType where S.Generator.Element == T>(s: S) { | |
// error: cannot convert expression's type S to type S | |
for v in s { | |
print(v) | |
} | |
} | |
} | |
// manually convert for...in to generator and while loop | |
struct B<T> { | |
func f<S: SequenceType where S.Generator.Element == T>(s: S) { | |
var g = s.generate() | |
// error: cannot convert the expression's type '()' to type 'Self.Element??' | |
while let v = g.next() { | |
print(v) | |
} | |
} | |
} | |
// explicit type in while loop solves the problem | |
struct C<T> { | |
func f<S: SequenceType where S.Generator.Element == T>(s: S) { | |
var g = s.generate() | |
// annotating v to be of type T fixes this | |
while let v: T = g.next() { | |
print(v) | |
} | |
} | |
} | |
// prints 123 | |
let c = C<Int>() | |
c.f([1,2,3]) | |
// but same solution doesn't work for the for...in version | |
struct D<T> { | |
func f<S: SequenceType where S.Generator.Element == T>(s: S) { | |
// error: Type of expression is ambiguous without more context | |
for v: T in s { | |
print(v) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment