【问题标题】:Conditional protocol conformance?条件协议一致性?
【发布时间】:2016-05-21 06:04:30
【问题描述】:

我想做这样的事情:

class SomeClass<Element> { }
extension SomeClass: SomeProtocol where Element: String { }

它告诉我:

带有约束的“SomeClass”类型的扩展不能有继承子句。

到目前为止,我可以发誓这是协议/扩展/通用/关联类型范式的基本功能之一。还有其他方法可以实现吗?

【问题讨论】:

标签: swift generics constraints protocols


【解决方案1】:

这是在 Swift 4.1 中实现的。

【讨论】:

    【解决方案2】:

    作为 Paul,您现在可以在 Swift 4 中做到这一点

    protocol Nameable {
        var name:String {get set}
    }
    func createdFormattedName<T:Nameable>(_ namedEntity:T) -> String where T:Equatable {
        //Only entities that conform to Nameable which also conform to equatable can call this function
        return "This things name is " + namedEntity.name
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 2020-12-31
      • 2018-05-20
      • 1970-01-01
      相关资源
      最近更新 更多