简体   繁体   中英

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

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?

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]"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM