【问题标题】:How to implement the CustomStringConvertible for a protocol in extension?如何为扩展中的协议实现 CustomStringConvertible?
【发布时间】:2019-10-03 17:18:21
【问题描述】:

我想在协议扩展中为我的协议实现一个可打印的功能,然后任何符合协议的结构都将根据协议的字段进行打印。但我收到以下错误,似乎 swift 不允许这样做。我应该扩展String 并为其添加init(_:Info) {...} 吗?

protocol Info {
    var name: String { get }
    var serial: Int { get }
}
struct Person : Info {
    var name = ""
    var serial = 0
}

extension Info : CustomStringConvertible {
                 ^~~~~~~~~~~~~~~~~~~~~~~
                 error: extension of protocol 'Info' cannot have an inheritance clause

    var description: String {
        return "\(name) + \(serial)"
    }
}
func print(info: Info) {
    print(info)
}

【问题讨论】:

标签: swift


【解决方案1】:

您应该在定义中继承协议,而不是在扩展中。

protocol Info: CustomStringConvertible {
    var name: String { get }
    var serial: Int { get }
}
struct Person : Info {
    var name = ""
    var serial = 0
}

extension Info  {
    var description: String {
        return "\(name) + \(serial)"
    }
}
func print(info: Info) {
    print(info)
}

【讨论】:

    【解决方案2】:

    您需要使您的协议符合CustomStringConvertible。然后在您的extensionInfo 中,您可以提供默认方法。如下。

    protocol Info: CustomStringConvertible {
        var name: String { get }
        var serial: Int { get }
    }
    
    struct Person: Info {
        var name = ""
        var serial = 0
    }
    
    extension Info {
        var description: String {
            return "\(name) + \(serial)"
        }
    }
    
    func print(info: Info) {
        print(info)
    }
    

    这是因为一致性需要一个约束,否则编译器认为它是一个继承

    另一种方法是执行以下操作:

    protocol Info {
        var name: String { get }
        var serial: Int { get }
    }
    
    struct Person: Info, CustomStringConvertible { // notice that Person now conforms to CustomStringConvertible
        var name = ""
        var serial = 0
    }
    
    // the extension only applies to objects that themselves conform to CustomStringConvertible
    extension Info where Self: CustomStringConvertible  {
        var description: String {
            return "\(name) + \(serial)"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多