Hello,
I'm trying to add JSON compliance to native Swift data types in a super lightweight fashion (possibly without adding another abstraction layer, which is useful for NSJSONSerialization etc.). Consider the following code:
protocol JSONValueType {}
extension String: JSONValueType {}
extension Int: JSONValueType {}
extension Double: JSONValueType {}
extension Bool: JSONValueType {}
extension NSNull: JSONValueType {}
// This method demonstrates that the approach works
func doWithJSONValue(jsonValue: JSONValueType) {
// ...
}
doWithJSONValue("Hello")
doWithJSONValue(100)
doWithJSONValue(3.1415)
doWithJSONValue(true)
doWithJSONValue(NSNull())This works and allows me to mark certain data types as JSON value types, which in turn allows me to write functions that only accept those types. Now valid JSON requires an array or a dictionary (with strings as keys) as top level element (and of course they can be nested too). So I tried to add another protocol extension to those data types as well:
protocol JSON {}
// This is what I actually want
func doWithJSON(json: JSON) {
// ...
}
// I'd start with the following, but
extension Dictionary where Key: String, Value: JSONValueType: JSON {}However this is not valid Swift 2 code. I'm wondering if I'm just doing it wrong or if there is another simple solution that I did not yet think of.