【问题标题】:Return a class that conforms to a swift protocol (the actual class, not an instance of it)返回一个符合 swift 协议的类(实际的类,而不是它的实例)
【发布时间】:2018-09-25 16:45:42
【问题描述】:

我在返回一个类而不是一个符合协议的实例时遇到了麻烦。这是可以做到的吗?这是我的代码的近似值:

public protocol MyProt {
    //things
}

var protConformer: MyProt {
    return boolVar ? ClassOne : ClassTwo // where both classes conform to MyProt
}

当然,我在这里收到错误消息"Cannot convert return expression of type 'ClassOne.Type' to return type 'MyProt'。关于这是否可能的任何想法?

【问题讨论】:

    标签: swift protocols swift-protocols


    【解决方案1】:

    你需要将protConformer的类型改为协议的元类型,即MyProt.Type,如果你想返回一个符合协议的type而不是这样的一个实例输入。

    var protConformer: MyProt.Type {
        return boolVar ? ClassOne.self : ClassTwo.self
    }
    

    【讨论】:

      【解决方案2】:

      MyProt 类型的意思是“一个采用 MyProt 的类型的实例”。如果你真的想操作元类型,语法是:

      var protConformer: MyProt.Type {
          return boolVar ? ClassOne.self : ClassTwo.self
      }
      

      但我必须警告你,这几乎不是正确的做法。您可能正在这里寻找一个泛型(无论您的实际问题是什么)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-21
        • 1970-01-01
        相关资源
        最近更新 更多