2

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?

Cory Juhlin
  • 364
  • 4
  • 9
  • https://stackoverflow.com/questions/38999102/generics-in-swift-generic-parameter-t-could-not-be-inferred this is a good read about generic inference – trndjc Dec 19 '18 at 22:07
  • 2
    In this case `DataSource.Index` is `Dictionary.Index` and not `String`. Other remark: better return `DataSource.Element?` instead of `Any?` – ielyamani Dec 19 '18 at 22:58
  • @Carpsen90 You are correct about the index. According to [Apple's documentation](https://developer.apple.com/documentation/swift/dictionary/index), the index isn't the type of the key at all, although you are able to subscript with just the key. – Cory Juhlin Dec 19 '18 at 23:20

0 Answers0