【问题标题】:how to declare a generate protocol as delegate?如何将生成协议声明为委托?
【发布时间】:2023-03-27 02:44:01
【问题描述】:

我们可以像下面这样生成协议:

protocol SomeDelegate {
    typealias T
    func xxx(x: T)
}

并使某些类符合它:

class AA: SomeDelegate {
    typealias T = Int
    func xxx(x: T) {
        // do some thing
    }
}

我的问题是如何声明一些符合生成协议的属性,如下所示:

class BB {
    var delegate: SomeDelegate
}

上面的代码会报错:

Protocol 'SomeDelegate' can only be used as a generic constraint 
because it has Self or associated type requirements 

看来我可以将协议用作委托,如下所示:

class BB {
    var delegate: AA?
}

但是,这不是我想要的,这会导致我的委托不能继承其他父类

【问题讨论】:

    标签: swift generics protocols


    【解决方案1】:

    您可以使用泛型,使用SomeDelegate 作为类型约束:

    class BB <U : SomeDelegate> {
       var delegate: U? = nil
    }
    

    这样你只需要在初始化BB的实例时提供U的类型:

    struct MyStruct : SomeDelegate {
        // The argument of xxx needs to be a concrete type here.
        func xxx(x: Int) {
            // ...
        }
    }
    
    let bb = BB<MyStruct>()
    

    【讨论】:

      【解决方案2】:

      有几种方法可以解决此错误。

      protocol SomeDelegate {
          typealias T
          func xxx(x: T)
      }
      

      首先为函数使用正确的类型类,编译器自行推断类型。

       class AA: SomeDelegate {
          func xxx(x: Int) {
              println(x)
          }
         }
      

      或者,您也可以覆盖 typealias 并为其分配适当的类型类,例如,

      class AA: SomeDelegate {
          typealias T = Int
          func xxx(x: T) {
              println(x)
          }
      }
      

      然后像以前那样使用它,

      class B {
          var someDelegate: AA?
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-16
        • 2020-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多