【问题标题】:Swift protocol to only implemented by specific classesSwift 协议仅由特定类实现
【发布时间】:2017-03-24 21:21:16
【问题描述】:

我想快速创建一个仅由特定类及其子类采用的协议。 我知道我可以使用这样的协议扩展

  protocol PeopleProtocol: class {
   }

   extension PeopleProtocol where Self: People {
   }

但我的协议中的方法将是一个init 方法,该方法将由一个类或其子类实现,并且只返回某些特定类型的对象。

类似的东西。

protocol PeopleProtocol: class {
   init() -> People
}

或者我可以做一些这样的事情

extension PeopleProtocol where Self : People {
   init()
}

但是有两个问题,

    1234563
  1. 在第二种方法中,我必须在协议扩展中提供一个函数体,所以这件事是毫无疑问的,因为我不知道要为这个通用实现返回什么特定类型。

所以任何建议我如何调用一个 init 方法并执行以下任一操作:

  1. 让协议(不是协议扩展)仅由特定类及其子类实现。
  2. 或者从协议扩展方法返回某个实例而不给出其主体。

【问题讨论】:

  • 基本上init 方法根本没有返回值。
  • 没错,这就是为什么我想首先添加一个限制,即该方法只能由特定的类类型实现。
  • 抱歉没听明白,你们是什么意思?在正文中使用Self,而不是协议限制的超类
  • 我看错了,删了评论。

标签: swift protocols protocol-extension


【解决方案1】:

您可以添加只为适当的类扩展的必需方法。

例如:

protocol PeopleProtocol
{
  var conformsToPeopleProtocol:Bool { get }
}

extension PeopleProtocol where Self:People
{
  var conformsToPeopleProtocol:Bool {return true}
}

class People  
{}

class Neighbours:People 
{}

extension Neighbours:PeopleProtocol // this works 
{}

class Doctors:People,PeopleProtocol // this also works
{}

class Dogs:PeopleProtocol // this will not compile
{}

这很容易被想要的程序员规避,但至少它会让编译器在你尝试将协议应用于其他类时警告你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    相关资源
    最近更新 更多