Search code examples
swiftxcode6swift-extensions

Use of undeclared type 'KeyType' in Dictionary extension (Swift)


With the beta 5 changes I'm running into an error related to KeyType and ValueType in the extension below.

extension Dictionary {

    func filter(predicate: (key: KeyType, value: ValueType) -> Bool) -> Dictionary {
        var filteredDictionary = Dictionary()

        for (key, value) in self {
            if predicate(key: key, value: value) {
                filteredDictionary.updateValue(value, forKey: key)
            }
        }

        return filteredDictionary
    }
}

I might be missing something, but I can't seem to find any related changes in the release notes and I know that this worked in beta 3.


Solution

  • The Dictionary declaration has changed to use just Key and Value for its associated types instead of KeyType and ValueType:

    // Swift beta 3:
    struct Dictionary<KeyType : Hashable, ValueType> : Collection, DictionaryLiteralConvertible { ... }
    
    // Swift beta 5:
    struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible { ... }
    

    So your extension just needs to be:

    extension Dictionary {
    
        func filter(predicate: (key: Key, value: Value) -> Bool) -> Dictionary {
            var filteredDictionary = Dictionary()
    
            for (key, value) in self {
                if predicate(key: key, value: value) {
                    filteredDictionary.updateValue(value, forKey: key)
                }
            }
    
            return filteredDictionary
        }
    }