关于protocol中使用Self的注意事项

由于Self具有运行时动态特性,实现protocol必须禁止类的继承,否则,由于类型确定导致编译器不通过,具体详见如下例子:

protocol AProtocol{
    func createViewController() -> Self?
}

final class BClass:AProtocol{
    func createViewController() -> BClass? {
        return BClass()
    }
}

上例中有两个关键点:

  1. 实现接口的类返回值为类的本身,而不是Self
  2. 类必须是final
posted @ 2017-02-10 12:27  oceannw  阅读(143)  评论(0编辑  收藏  举报