Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension of type Array with constraints cannot have an inheritance clause - swift 2 [duplicate]

In swift 2 I want to extend Array type. I have a JSONDecodable protocol. What i want to say to compiler is conform Arrayto 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?

like image 917
mustafa Avatar asked Oct 08 '15 08:10

mustafa


1 Answers

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
        }
    }
}
like image 176
ipaboy Avatar answered Nov 10 '22 06:11

ipaboy