iosswiftprotocolsprotocol-extension

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?


Solution

  • Swift 4.2

    In Swift 4.2 I was able to extend an array with the elements conforming to a protocol like this:

    public extension Array where Element: CustomStringConvertible{
        public var customDescription: String{
            var description = ""
            for element in self{
                description += element.description + "\n"
            }
    
            return description
        }
    }