Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend Array to conform to protocol if Element conforms to given protocol

I'd like to do something like this, but can't get the syntax right or find anywhere on the web that gives the right way to write it:

protocol JSONDecodeable {
    static func withJSON(json: NSDictionary) -> Self?
}

protocol JSONCollectionElement: JSONDecodeable {
    static var key: String { get }
}

extension Array: JSONDecodeable where Element: JSONCollectionElement {
    static func withJSON(json: NSDictionary) -> Array? {
        var array: [Element]?
        if let elementJSON = json[Element.key] as? [NSDictionary] {
            array = [Element]()
            for dict in elementJSON {
                if let element = Element.withJSON(dict) {
                    array?.append(element)
                }
            }
        }
        return array
    }
}

So I want to conform Array to my protocol JSONDecodeable only when the elements of this array conform to JSONCollectionElement.

Is this possible? If so, what's the syntax?

like image 482
kylejm Avatar asked Oct 19 '15 16:10

kylejm


1 Answers

This isn't possible yet in Swift. You can see the same thing happen in the standard library: Array doesn't gain Equatable conformance when it's declared with Equatable elements.

like image 103
Nate Cook Avatar answered Nov 08 '22 13:11

Nate Cook