简体   繁体   English

如何创建扩展以允许自定义类型的数组符合协议?

[英]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". 我有一个自定义类型Banana和我想创建的扩展Array (或,如果非要, Sequence )的Banana ,以符合协议CustomStringConvertible使得主叫description的阵列上的Banana将返回“一串香蕉”。 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). 您可以限制扩展,但是受限制的扩展不能包含继承子句(上面链接的Swift提案 @Code Different正是您想要的)。

One workaround would be to make the constrained extension, but just add your own property, rather than having it conform to CustomStringConvertible . 一种解决方法是制作受限制的扩展名,而只需添加您自己的属性,而不是使其符合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 . 同样值得注意的是, Array已经符合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. 您可以在香蕉类printDescription中创建一个自定义方法,该方法将打印所需的描述。 No need to create the extension in this case. 在这种情况下,无需创建扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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