Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Last active August 29, 2015 14:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airspeedswift/a40d9e70f813863ab324 to your computer and use it in GitHub Desktop.
Save airspeedswift/a40d9e70f813863ab324 to your computer and use it in GitHub Desktop.
Swift for…in generic inference prob
// 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