Protocol Initializer Inheritance

I am trying to construct an object that conforms to a protocol `A` and also sublclasses object `B`. Protocol `A` requires an initializer that will be used to construct it. Xcode will attempt to autocomplete the initializer but then ultimately gives the following error:

`error: argument passed to call that takes no arguments`

Here is some sample code:

protocol MyProtocol {
  init(foo: Int, bar: String)
}

class MyOperation: Operation, MyProtocol {
  required init(foo: Int, bar: String) {
      super.init()
  }
}

func makeMyProto<T: MyProtocol>() -> T where T: Operation {
  return T(foo: 0, bar: "bar")
}

It’s worth noting that this only fails when subclassing `Operation`. Subclassing `NSObject` or several other objects seems to work. Hopefully there is a way to do this. Ultimately, I just want this generic method to construct a thing that is both an `Operation` and conforms to a protocol.

Any help here would be greatly appreciated. Thanks!
-Bradley

I think this is a known issue. You can work around it by jumping through another function:

import Foundation
protocol MyProtocol {
init(foo: Int, bar: String)
}

class MyOperation: Operation, MyProtocol {
required init(foo: Int, bar: String) {
     super.init()
}
}

private func makeMyProtoHelper<T: MyProtocol>() -> T {
return T(foo: 0, bar: "bar")
}

func makeMyProto<T: MyProtocol>() -> T where T: Operation {
  return makeMyProtoHelper()
}

Jordan

···

On Nov 18, 2016, at 16:45, Bradley Zeller via swift-users <swift-users@swift.org> wrote:

I am trying to construct an object that conforms to a protocol `A` and also sublclasses object `B`. Protocol `A` requires an initializer that will be used to construct it. Xcode will attempt to autocomplete the initializer but then ultimately gives the following error:

`error: argument passed to call that takes no arguments`

Here is some sample code:

protocol MyProtocol {
 init(foo: Int, bar: String)
}

class MyOperation: Operation, MyProtocol {
 required init(foo: Int, bar: String) {
     super.init()
 }
}

func makeMyProto<T: MyProtocol>() -> T where T: Operation {
 return T(foo: 0, bar: "bar")
}

It’s worth noting that this only fails when subclassing `Operation`. Subclassing `NSObject` or several other objects seems to work. Hopefully there is a way to do this. Ultimately, I just want this generic method to construct a thing that is both an `Operation` and conforms to a protocol.

Any help here would be greatly appreciated. Thanks!
-Bradley
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users