I am writing some code that, ideally, would be able to operate on anything that can be subscripted with a String
. Here's an example:
class MyClass {
func getValue<DataSource>(key: String, from dataSource: DataSource) -> Any? where DataSource: Collection, DataSource.Index == String {
return dataSource[key]
}
}
let data: [String: Any] = [
"why": "is this not working"
]
MyClass().getValue(key: "why", from: data) // Compile error!
The error I receive is Generic parameter "DataSource" could not be inferred
. I cannot figure out why this is not valid code. I have a feeling there's some nuance of covariance/contravariance that I have not digested properly. In any case, is it even possible to accomplish what I am trying to do?