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

swift extension where
there cannot be more than one conformance, even with different conditional bounds
swift conditional conformance
swift extend array with 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?

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
    }
}

One thing that is very common when working with protocols like the above is to that is to add an extension on Array for when its Element type conforms to Now, in Swift 4.1, we can make Array conform to ScoreConvertible only if it To be able to load an array of articles for a given category, we define an  For your Array extension, watch the video again, especially at 3:06 where Pasan extends Array to make the type's Elements conform to his protocol. You want to use the same syntax he uses. You want to use the same syntax he uses.

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.

Can't extend Array of elements conforming to Protocol And if edit the extension definition by replacing : with == , it will not work, in other denote conformance, and protocols do not conform to themselves, which means that  Given a protocol P and a struct S conforming to P.. I have difficulties extending SequenceType such that it works on an array of type [P] as well as [S]. The following example illustrates my problem.

I would suggest using a wrapper. For instance

struct ArrayContainer<T: Decodable>: Container {
    let array: [T]
}

I'm extending Array for a custom Element type to add a mutating function. protocol Value {} struct StringValue: Value { let value: String } struct IntValue: Value Array where Element: Value { mutating func chain(_ newValue: Element) { if let you could use Any , an enum wrapper or an erased type that conforms to Value . I want to create a class that can store objects conforming to a certain protocol. The objects should be stored in a typed array. According to the Swift documentation protocols can be used as types

I don't know if this is the best approach or if apple intended it to be used this way. I used this once and it worked well for me:

Say you have the following protocol

protocol MyProtocol {
    var test: Bool { get }
}

You can do this for Arrays

extension Array: MyProtocol where Element: MyProtocol {
    var test: Bool {
        return self.allSatisfy({ $0.test })
    }
}

And this for Dictionaries

extension Dictionary: MyProtocol where Value: MyProtocol {
    var test: Bool {
        return self.values.allSatisfy({ $0.test })
    }
}

Swift is a fantastic way to write software, whether it's for phones, desktops, 2 // original Stack<Element> implementation 3 var items = [Element]() 4 mutating func This means that you can extend Array to conform to the Container protocol in a protocol, to require that conforming types satisfy the constraints described by  Alternatively, use this method to sort a collection of elements that do conform to Comparable when you want the sort to be descending instead of ascending. Pass the greater-than operator (>) operator as the predicate.

Structs, classes and enumerations can conform to a protocol: It is possible to declare that the conforming type of a protocol must be class, It can also precise if that property should be at least read-only or settable as well array, because Swift's type inference doesn't search for matching protocols, only for concrete types  Your class or enum just has to implement the generate () function that returns a Generator. If you click on the Generator in the documentation, you get the following protocol: So the object that conforms to the Generator protocol has to implement a next () function that returns an Element.

Let's modify our generic stack to conform to protocol: }extension Array: Container {} in a protocol to require that conforming types satisfy those constraints. Now, Stack's Element type needs to conform to Equatable else it will give When you extend a generic type, you don't provide a type parameter  When you want to sort a sequence of elements that don't conform to the Comparable protocol, pass a predicate to this method that returns true when the first element passed should be ordered before the second. The elements of the resulting array are ordered according to the given predicate.

Notice that when we extend a protocol, we use the same syntax and format that we use Now, every type that conforms to the Collection protocol will receive the the newArray array will contain the elements 1, 3, 5, 7, and 9, because those it is important to know what types conform to the protocol we are extending. These three capabilities match the requirements of the Container protocol. This means that you can extend Array to conform to the Container protocol simply by declaring that Array adopts the protocol. You do this with an empty extension, as described in Declaring Protocol Adoption with an Extension:

Comments
  • Use generics something like Array<JSONCollectionElement>
  • Confirmed! Thank you! I had a quick look around for some info on this change in Swift 4.2, but couldn't find any. If anyone's got it please share!
  • @OrkhanAlikhanov still not possible. I am getting a Extension of type 'Array' with constraints cannot have an inheritance clause build time error from XCode.