Last active
August 29, 2015 14:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
}
}
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
}
}
Thank you, Erica! I'm going to dive into this and try to understand it better.
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
Look at the type of testDict. It's NSDictionary not Dictionary.