I've got a quick question regarding generics in Swift. The problem is I'm trying to store a variable that takes a generic as a parameter, but am unable to cast it up to the type it is restricted by. It's best explained in a short example:
class Foo { }
class Thing<T: Foo> {
func produceBar() -> Bar {
return Bar(aThing: self as! Thing<Foo>)
}
}
class Bar {
var thing: Thing<Foo>
init(var aThing: Thing<Foo>) {
self.thing = aThing
}
}
The code above produces the error: "Cast from Thing<T> to unrelated type Thing<Foo> always fails"
Shouldn't it never fail, since T is restricted to being a subclass of Foo? I must be misunderstanding the way generics work in Swift, any guidance or help would be much appreciated!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…