Last active
August 31, 2016 02:25
-
-
Save mwrites/96f662d3f12fd9c2b63d7156938acaee to your computer and use it in GitHub Desktop.
This file contains hidden or 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
protocol StringValueExpressible { | |
var stringValue: String { get } | |
} | |
extension String : StringValueExpressible { | |
var stringValue: String { | |
get { return self } | |
} | |
} | |
protocol DictionaryConvertable { | |
static func fromDictionary(dic: [String:AnyObject]) throws -> Self | |
} | |
enum DictionaryParseError : ErrorType { | |
case KeyInvalid | |
case KeyNotFound(String) | |
case TypeInvalid | |
} | |
extension Dictionary where Key: StringValueExpressible { | |
// extract key (Key) from dictionary of type T which can be deserialized from dictionary (conforms to DictionaryConvertable) | |
// try dic.parseKey("car", asType: Car.self) | |
func parseKey<T: DictionaryConvertable>(key: Key, asType type: T.Type) throws -> T { | |
guard let item = self[key] else { | |
throw DictionaryParseError.KeyNotFound(key.stringValue) | |
} | |
guard let itemDic = item as? [String:AnyObject] else { | |
throw DictionaryParseError.TypeInvalid | |
} | |
let typedItem: T = try T.fromDictionary(itemDic) | |
return typedItem | |
} | |
// extract key (Key) from dictionary of type T | |
// try dic.parseKey("carName", asType: String.self) | |
func parseKey<T>(key: Key, asType type: T.Type) throws -> T { | |
guard let item = self[key] else { | |
throw DictionaryParseError.KeyNotFound(key.stringValue) | |
} | |
guard let typedItem = item as? T else { | |
throw DictionaryParseError.TypeInvalid | |
} | |
return typedItem | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment