0

我想在协议扩展中为我的协议实现一个可打印的功能,然后任何符合协议的结构都将根据协议的字段进行打印。但我收到以下错误,似乎 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)
}
4

2 回答 2

3

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

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)
}
于 2019-10-03T09:07:24.070 回答
3

您需要使您的协议符合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)"
    }
}
于 2019-10-03T09:08:28.983 回答