How do I create an extension to allow an array of a custom type to conform to a protocol?

589 views Asked by At

I have a custom type Banana and I would like to create an extension of Array (or, If I have to, Sequence) of Banana to conform to the protocol CustomStringConvertible so that calling description on the array of Banana would return "A bunch of bananas". Is this possible and, if so, how would I go about doing this?

2

There are 2 answers

0
zpasternack On BEST ANSWER

Short answer: no.

You can constrain an extension, but a constrained extension can't contain an inheritance clause (the Swift proposal @Code Different linked above is exactly what you're looking for).

One workaround would be to make the constrained extension, but just add your own property, rather than having it conform to CustomStringConvertible.

class Banana : CustomStringConvertible {
    var description: String {
        return "a banana"
    }
}

let aBanana = Banana()
aBanana.description // "a banana"

extension Array where Element: Banana {
    var bananaDescription: String {
        return "a bunch of bananas"
    }
}

let bananas = [Banana(), Banana(), Banana()]
bananas.bananaDescription // "a bunch of bananas"

Worth noting, too, that Array already conforms to CustomStringConvertible.

let bananas = [Banana(), Banana(), Banana()]
bananas.description // "[a banana, a banana, a banana]"
1
Bryan On

You could create a custom method in your banana class, printDescription, which would print your desired description. No need to create the extension in this case.