【问题标题】:Passing a swift Class to Generic Function将 swift 类传递给泛型函数
【发布时间】:2015-06-26 13:27:58
【问题描述】:

我正在尝试使用泛型动态创建基于类实例的类型,但是我遇到了一些奇怪的行为。在示例 1 中,一切正常,但在示例 2 中,如果我将 Test.self 传递给泛型函数,则它不起作用。类型是一样的,一切都是一样的,我不明白为什么。

class Test{
  required init(x: Int){
    // Do Something
  }
}

class Builder{
  init(){
  }

  func use<T>(test2: T.Type) -> Void{
    test2(x: 10) // Error: T cannot be constructed because it has no accessible initializers 
  }
}

// Example 1:
let test1 = Test.self
test1(x: 10)

// Example 2:
let builder = Builder()
builder.use(Test.self)

【问题讨论】:

    标签: swift introspection


    【解决方案1】:

    这是因为T 不是Test 类型。要解决这个问题:

    class Builder{
      init(){
      }
    
      // T has to be of type Test or is a subclass of Test
      func use<T: Test>(test2: T.Type) -> Void{
        test2(x: 10)
      }
    }
    

    【讨论】:

      【解决方案2】:

      当您定义use&lt;T&gt; 函数时,您必须以某种方式告诉它您所传递的类将有一个init(x:) 构造函数。

      您可以通过声明协议并使可选类型T 符合该协议来做到这一点。

      试试这个:

      protocol TestProtocol {
          init(x:Int)
      }
      
      class Test: TestProtocol {
          required init(x: Int){
              // Do Something
          }
      }
      
      class Builder{
          init(){
          }
      
          func use<T: TestProtocol>(test2: T.Type) -> TestProtocol {
              return test2(x: 10)
          }
      }
      

      PD:在 Swift 1.2 上测试

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-20
        • 2018-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多