Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
I'm attempting to create a constrained extension on Dictionary that only applies to String-keyed dictionaries.
import Foundation
extension Dictionary where Key:String {
func methodThatOnlyMakesSenseWhenKeysAreStrings() -> [Key : Value] {
var resultDict = [Key : Value]
for key in self.keys {
let reversedKey = String(key.characters.reverse())
resultDict[reversedKey] = self[key]
}
return resultDict
}
}
let testDict = ["one" : 1, "two" : "dos", "three" : NSNumber(char: 3)]
let reverseDict = testDict.methodThatOnlyMakesSenseWhenKeysAreStrings()
// Error: [String:NSObject] doesn't have member named methodThatOnlyMakesSenseWhenKeysAreStrings
@erica

This comment has been minimized.

Copy link

@erica erica commented Aug 6, 2015

Look at the type of testDict. It's NSDictionary not Dictionary.

@erica

This comment has been minimized.

Copy link

@erica erica commented Aug 6, 2015

protocol StringType {}
extension String: StringType {}

public extension SequenceType {
    func mapDo(p: (Self.Generator.Element) -> Void) {
        for x in self {p(x)}
    }
}

extension Dictionary where Key:StringType {
    func methodThatOnlyMakesSenseWhenKeysAreStrings() -> [String:Value] {
        var resultDict = [String:Value]()
        self.mapDo({(key, value) in
            let reversedKey = String(String(key).characters.reverse())
            resultDict[reversedKey] = self[key]})
        return resultDict
    }
}
@erica

This comment has been minimized.

Copy link

@erica erica commented Aug 6, 2015

But I like this better

protocol Reversible {
    var reversed : Self {get}
}

extension String: Reversible {
    var reversed : String {return String(self.characters.reverse())}
}


public extension SequenceType {
    func mapDo(p: (Self.Generator.Element) -> Void) {
        for x in self {p(x)}
    }
}

extension Dictionary where Key:Reversible {
    func methodThatOnlyMakesSenseWhenKeysAreStrings() -> [Key:Value] {
        var resultDict = [Key:Value]()
        self.mapDo({(key, value) in
            resultDict[key.reversed] = self[key]})
        return resultDict
    }
}
@JoshuaSullivan

This comment has been minimized.

Copy link
Owner Author

@JoshuaSullivan JoshuaSullivan commented Aug 6, 2015

Thank you, Erica! I'm going to dive into this and try to understand it better.

@JoshuaSullivan

This comment has been minimized.

Copy link
Owner Author

@JoshuaSullivan JoshuaSullivan commented Aug 8, 2015

Ahh, I see. The extension constraint can only specify protocols, not types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.