首页 文章

如何要求协议只能由特定类采用

提问于
浏览
50

我想要这个协议:

protocol AddsMoreCommands {
     /* ... */
}

只能从继承自 UIViewController 类的类中采用 . This page告诉我,我可以通过编写指定它只由类(而不是结构)采用

protocol AddsMoreCommands: class {
}

但是我看不出如何要求它只被特定的类所采用 . That page later谈到将 where 子句添加到协议扩展以检查一致性,但我看不出如何适应它 .

extension AddsMoreCommands where /* what */ {
}

有没有办法做到这一点?谢谢!

3 回答

  • 33
    protocol AddsMoreCommands: class {
        // Code
    }
    
    extension AddsMoreCommands where Self: UIViewController {
        // Code
    }
    
  • 70

    这也可以在没有扩展的情况下实现:

    protocol AddsMoreCommands: class where Self: UIViewController {
       // code
    }
    

    EDITED 2017/11/04 :正如Zig所指出的,这似乎在Xcode 9.1上产生了警告 . 目前,Swift项目报告了一个问题(SR-6265)以删除警告,我将密切关注它并相应地更新答案 .

    如果存储实例的变量需要较弱(例如委托),则需要 EDITED 2018/09/29class . 如果你不需要弱变量,你可以省略 class ,只需编写以下内容,就不会有任何警告:

    protocol AddsMoreCommands where Self: UIViewController {
       // code
    }
    
  • 40

    由于上一个答案中存在问题,我最终得到了这个声明:

    protocol AddsMoreCommands where Self : UIViewController { 
        // protocol stuff here  
    }
    

    Xcode 9.1中没有警告

相关问题