简体   繁体   中英

Extracting values of multiple keys at once from a Swift dictionary

I was playing around with some possible ways to extract several 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 this:

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

In other words, it seems like it should be possible to implement multiSubscript() generically for any SequenceType-conformant subscript type.

However, Swift doesn't seem to 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's type 'S' to type 'S'
            result += self[seqElt]
        }
        return result
    }
}

This seems like a relatively straightforward use of constraints on generics. Does anyone see what I'm doing wrong?

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

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

I'm not entirely sure why for seqElt in seq doesn't work (I suspect a bug), but using SequenceOf<Key>(seq) in the for-in works:

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] didn't work; I used result.append(self[seqElt]) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM