In swift 2 I want to extend Array type. I have a JSONDecodable
protocol. What i want to say to compiler is conform Array
to protocol JSONDecodable
if elements of Array
are also JSONDecodable
. Here is the code:
public protocol JSONDecodable {
static func createFromJSON(json: [String: AnyObject]) throws -> Self
}
extension Array: JSONDecodable where Element: JSONDecodable {
}
But compiler gives the error: "Extension of type Array with constraints cannot have an inheritance clause"
So is there any other way to accomplish this kind of behavior?
how about little type erasure? It should do the tick
protocol JSONDecodable {
init(json: JSON) throws
}
While Swift 3 doesn't allow do like extension
extension Array: JSONDecodable where Element: JSONDecodable
but its possible to do:
extension Array: JSONDecodable {
init(json: JSON) throws {
guard let jsonArray = json.array,
let decodable = Element.self as? JSONDecodable.Type else {
throw JSONDecodableError.undecodable
}
self = jsonArray.flatMap { json in
let result: Element? = (try? decodable.init(json: json)) as? Element
return result
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With