Skip to content

Instantly share code, notes, and snippets.

@JoshuaSullivan
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaSullivan/cd2561993201069ab7bf to your computer and use it in GitHub Desktop.
Save JoshuaSullivan/cd2561993201069ab7bf to your computer and use it in GitHub Desktop.
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
Copy link

erica commented Aug 6, 2015

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

@erica
Copy link

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
Copy link

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
Copy link
Author

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

@JoshuaSullivan
Copy link
Author

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