嵌套在类中的Swift协议

时间:2016-03-17 16:33:51

标签: swift swift-protocols

我想在我的类中嵌套一个协议来实现委托模式,如下所示:

class MyViewController : UIViewController {

    protocol Delegate {
        func eventHappened()
    }

    var delegate:MyViewController.Delegate?

    private func myFunc() {
        delegate?.eventHappened()
    }
}

但是编译器不会允许它:

  

协议'代表'不能嵌套在另一个声明

我可以通过在课堂范围之外宣布MyViewControllerDelegate来轻松地使其发挥作用 我的问题是为什么这样的限制?

3 个答案:

答案 0 :(得分:14)

根据swift documenation

  

Swift使您能够定义嵌套类型,从而在它们支持的类型定义中嵌套支持枚举,类和结构。

鉴于协议不在该列表中,它似乎不会出现当前支持的协议。 他们可能会在某些时候添加这个功能,(Swift宣布不到两年就会发布)。任何关于他们为什么不会赢或不知道的想法都会引起我的猜测。

答案 1 :(得分:6)

这是我的解决方法:

  protocol MyViewControllerDelegate : class {
     func eventHappened()
  }
  class MyViewController : UIViewController {
     typealias Delegate = MyViewControllerDelegate
     weak var delegate: Delegate?

     private func myFunc() {
         delegate?.eventHappened()
     }

  }

答案 2 :(得分:-6)

您班级的另一个问题是delegate没有具体类型。您可以将其声明为MyViewController.Delegate?,因为它是可选类型,可以是.None。但这只会使您的私人myFunc死密码。只有枚举,类和结构可以符合协议。这三种类型中的哪一种是delegate

那就是说,这不是你问题的原因。当我为delegate创建一个真实类型并使其符合Delegate协议时,我仍会遇到相同的错误。

class MyViewController: UIViewController {

  protocol Delegate {
    func eventHappened()
  }

  class Classy: Delegate {
    func eventHappened() {
      print("eventHappened")
    }
  }

  var delegate: Classy? = Classy()

  func myFunc() {
    delegate?.eventHappened()
  }
}

enter image description here

作为一种深奥的练习,这可能会有助于推动类可能做的事情的界限,但是没有人应该尝试在类中声明协议。协议都是关于类型组合和集合的。当您被限制在同一外层时,没有代码重用方案。

相关问题