I want to define a type that can be serialized to a valid JSON object
So for instance if a JSON can contain the following:
String
Number
Array
Object
Date
Boolean
I would like to define a protocol with valid types
protocol JsonSerializable {
}
typealias JSONObject = [String : JsonSerializable]
typealias JSONArray = [JsonSerializable]
// foundation implements serializing numbers + strings + dates etc. to JSON
extension String : JsonSerializable {}
extension Int : JsonSerializable {}
// problem with defining dictionary and array of JSON-able types
extension Dictionary : JsonSerializable {}
...
The question is how can I make sure that the dictionary only contains serializable types (at compile time)
Firstly I would recommend you read Empowering Extensions in Swift 2: Protocols, Types and Subclasses (Xcode 7 beta 2). (Since it's for beta 2 there have been a few minor changes)
Back to your problem. For Array
:
extension Array where Element: JsonSerializable {
var json: String { ... }
}
[1, 2, 3].json // Valid
[true, false].json // Invalid; `Bool` doesn't conform to `JsonSerializable`.
Dictionary is a bit trickier because, as said in the mentioned article:
The current rules of extending a generic type in this way is that the type being referenced after the where keyword must be a class or a protocol.
Therefore you can't specify that the Key
of the Dictionary
must be a String
. The workaround given in the article is to define a StringType
protocol:
protocol StringType {
var characters: String.CharacterView { get }
}
extension String: StringType {}
Now for the Dictionary Extension:
extension Dictionary where Key: StringType, Value: JsonSerializable {
var json: String { ... }
}
["A": 1, "B": 2].json // Valid
[1: "1", 2: "2"].json // Invalid; `Int` doesn't conform to `StringType`.
["A": true, "B": false].json // Invalid; `Bool` doesn't conform to `JsonSerializable`.
Alternatively, you could create your own JsonArray
and JsonDictionary
types, which would be backed by an Array
or Dictionary
respectively:
struct JsonArray<Element: JsonSerializable> {
private var array: [Element]
...
}
extension JsonArray: ArrayLiteralConvertible {
init(arrayLiteral elements: Element...) {
self.init(array: elements)
}
}
struct JsonDictionary<Value: JsonSerializable> {
private var dictionary: [String: Value]
...
}
extension JsonDictionary: DictionaryLiteralConvertible {
init(dictionaryLiteral elements: (String, Value)...) {
var temp = [String: Value]()
for (key, value) in elements {
temp[key] = value
}
self.init(dictionary: temp)
}
}
let array: JsonArray = [1, 2, 3]
let dictionary: JsonDictionary = ["A": 1, "B": 2]
As far as I know, it is impossible today in Xcode 7 beta 6.
You can duplicate this radar if you want: http://openradar.appspot.com/radar?id=5623386654900224
来源:https://stackoverflow.com/questions/32475439/swift-define-a-recursive-type-with-a-protocol