Extracting values ​​of multiple keys at once from a Swift dictionary

I've been playing around with several possible ways to extract multiple values ​​at once from a Swift dictionary. The goal is to do something like this:

var dict = [1: "one", 2: "two", 3: "three"]
dict.multiSubscript(2...4) // Should yield ["two", "three", nil]

      

or that:

dict.multiSubscript([1, 2]) // Should yield ["one", "two"]

      

In other words, it seems that it should be possible to implement multiSubscript()

in general for any type of SequenceType compatible indexes.

However, Swift doesn't seem to be like the following implementation and the error message isn't very illuminating:

extension Dictionary {
    func multiSubscript<S: SequenceType where S.Generator.Element == Key>(seq: S) -> [Value?] {
        var result = [Value?]()
        for seqElt in seq { // ERROR: Cannot convert the expression type 'S' to type 'S'
            result += self[seqElt]
        }
        return result
    }
}

      

This is similar to the relatively straightforward use of generics restrictions. Does anyone see what I am doing wrong?

For bonus points, is there a way to implement this to allow the use of the standard signature syntax? For example:

dict[2...4] // Should yield ["two", "three", nil]

      

+3


source to share


1 answer


I'm not really sure why it for seqElt in seq

doesn't work (I suspect it's a bug), but using SequenceOf<Key>(seq)

in internal functions:

func multiSubscript<S: SequenceType where S.Generator.Element == Key>(seq: S) -> [Value?] {
    var result = [Value?]()
    for seqElt in SequenceOf<Key>(seq) {
        result.append(self[seqElt])
    }
    return result
}

      



Also note that result += self[seqElt]

doesn't work; I used instead result.append(self[seqElt])

.

+1


source







All Articles