【问题标题】:How to create constraint on protocol如何对协议创建约束
【发布时间】:2017-02-08 18:05:07
【问题描述】:

我尝试创建只能由继承自 UIView 的类实现的协议,当这段代码编译时没有错误(在 Swift 3.0 中)时,我感到惊讶:

protocol TestsProtocol {
    func test()
}

extension TestsProtocol where Self: UIView { }

class FooClass: TestsProtocol {

    func test() {

    }
}

我们可以看到FooClass 不继承自UIView,使用协议扩展我不想强制只有从UIView 继承的类才能实现它。 据我记得这不会在 Swift 2.1 中编译

【问题讨论】:

  • 我想不出为什么它不能在 Swift 2.1 中编译的原因——协议扩展不限制哪些类型可以符合协议,它们只是让你添加默认实现。但真正的问题是,如果一个类型可以满足所有协议的要求,为什么不应该允许它符合,除非它也是UIView
  • extension that can only be applied on a given class type 的可能副本——尽管我不相信那里的答案能完全达到你想要的。答案很简单,你不能根据一致性类型来限制对协议的一致性。

标签: ios swift swift-protocols


【解决方案1】:

你不能在 Swift 中做到这一点。扩展语法还有其他作用:

extension TestsProtocol where Self: UIView {
    func useful() {
        // do something useful
    }
}

现在任何实现了 TestsProtocol 并且是 UIView(或子类)的类也具有有用的()函数。

【讨论】:

    【解决方案2】:

    您可以通过限制协议轻松地做到这一点,使其可以从 UIView 以外的任何类型扩展:

    protocol TestsProtocol:UIView {
        func test()
    }
    
    class FooClass: TestsProtocol {
    
        func test() {
    
        }
    }
    

    所以这会导致编译错误

    “TestsProtocol”要求“FooClass”继承自“UIView”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      相关资源
      最近更新 更多