I want to store a more specialized type in a Dictionary of type [String:SomeClass]. Here is some sample code illustrating my problem (also available to play with at https://swiftlang.ng.bluemix.net/#/repl/579756cf9966ba6275fc794a):
class Thing<T> {}
protocol Flavor {}
class Vanilla: Flavor {}
var dict = [String:Thing<Flavor>]()
dict["foo"] = Thing<Vanilla>()
It produces the error ERROR at line 9, col 28: cannot assign value of type 'Thing<Vanilla>' to type 'Thing<Any>?'
.
I've tried casting Thing<Vanilla>() as Thing<Flavor>
but that produces the error cannot convert value of type 'Thing<Vanilla>' to type 'Thing<Flavor>' in coercion
.
I've also tried to define the Dictionary as type [String:Thing<Any>]
but that doesn't change anything either.
How do I create a collection of different Thing
s without resorting to plain [String:AnyObject]
?
I should also mention that the class Thing
is not defined by me (in fact it's about BoltsSwift Task
s), so the solution to create a base class of Thing
without a type parameter doesn't work.