I have problem with declaring an Array and initialize it with many different generic items and in the same time use those items individually with generic support. Lets look at this:
protocol Item {
associatedtype ValueType: Any
var value: ValueType? { get set }
}
class ItemClass<T: Any>: Item {
typealias ValueType = T
var value: ValueType?
}
let intItem = ItemClass<Int>()
let stringItem = ItemClass<String>()
let array: [ItemClass<Any>] = [intItem, stringItem]
// Iterate over items and use `value` property as Any?
for item in array {
let val: Any? = item.value
// do something with val
}
// Individual usage with generic types support
let intValue: Int? = intItem.value
let stringValue: String? = stringItem.value
Why there is an error in array declaration like this:
Cannot convert value of type 'ItemClass<Int>' to expected element type 'ItemClass<Any>'
ItemClass<Any>andItemClass<Int>are completely unrelated types.valueproperty but since this is in array I can have different types of this property that should cast toAny.let array: [ItemClass] = ...then I have the same problem. I know I'm castingItemClass<Int>toItemClass. I can not uselet array: [Item]because ofProtocol 'Item' can only be used as a generic constraint because it has Self or associated type requirements. I don't know what to do in this situation.ItemClassis called type erasure, but even that won't help, since even with a type erasedAnyItemtype, you'll only be able to storeItems in anArraywhosevalueproperty is of the same type. What you are trying to achieve isn't possible with your current setup. Why isitemeven aprotocol? Why isn't it simply a genericstructin the first place? If your real problem is more complex than this, then include your real problem, not a contrived example.