1111public enum JSONEncodableError : ErrorType , CustomStringConvertible {
1212 case IncompatibleTypeError( elementType: Any . Type )
1313 case ArrayIncompatibleTypeError( elementType: Any . Type )
14+ case DictionaryIncompatibleTypeError( elementType: Any . Type )
1415 case ChildIncompatibleTypeError( key: String , elementType: Any . Type )
1516 case TransformerFailedError(
1617 key: String
@@ -22,6 +23,8 @@ public enum JSONEncodableError: ErrorType, CustomStringConvertible {
2223 return " JSONEncodableError: Incompatible type \( elementType) "
2324 case let . ArrayIncompatibleTypeError( elementType: elementType) :
2425 return " JSONEncodableError: Got an array of incompatible type \( elementType) "
26+ case let . DictionaryIncompatibleTypeError( elementType: elementType) :
27+ return " JSONEncodableError: Got an dictionary of incompatible type \( elementType) "
2528 case let . ChildIncompatibleTypeError( key: key, elementType: elementType) :
2629 return " JSONEncodableError: Got incompatible type \( elementType) for key \( key) "
2730 case let . TransformerFailedError( key: key) :
@@ -77,6 +80,21 @@ public extension Array {//where Element: JSONEncodable {
7780
7881// Dictionary convenience methods
7982
83+ public extension Dictionary { //where Key: String, Value: JSONEncodable {
84+ public func toJSON( ) throws -> AnyObject {
85+ var result : [ String : AnyObject ] = [ : ]
86+ for (k, item) in self {
87+ if let item = item as? JSONEncodable {
88+ result [ String ( k) ] = try item. toJSON ( )
89+ }
90+ else {
91+ throw JSONEncodableError . DictionaryIncompatibleTypeError ( elementType: item. dynamicType)
92+ }
93+ }
94+ return result
95+ }
96+ }
97+
8098public extension Dictionary where Value: AnyObject {
8199 public mutating func encode( value: Any , key: Key ) throws {
82100 let actualValue : Any
@@ -107,6 +125,15 @@ public extension Dictionary where Value: AnyObject {
107125 self [ key] = ( result as! Value )
108126 }
109127
128+ // test for dictionary
129+ else if let dict = actualValue as? JSONDictionary {
130+ if dict. dictionaryIsJSONEncodable ( ) {
131+ let encodableDict = dict. dictionaryMadeJSONEncodable ( )
132+ let result = try encodableDict. toJSON ( )
133+ self [ key] = ( result as! Value )
134+ }
135+ }
136+
110137 // incompatible type
111138 else {
112139 throw JSONEncodableError . ChildIncompatibleTypeError ( key: key as! String , elementType: actualValue. dynamicType)
0 commit comments