非标称类型X不支持显式初始化

我试图了解我在swift中对generics做错了什么。

我创建了这个示例游乐场

import UIKit public protocol MainControllerToModelInterface : class { func addGoal() init() } public protocol MainViewControllerInterface : class { associatedtype MODELVIEW var modelView: MODELVIEW? {get set} init(modelView: MODELVIEW) } public class MainViewController : UIViewController, MainViewControllerInterface where M : MainControllerToModelInterface { public weak var modelView: M? required public init(modelView: M) { self.modelView = modelView super.init(nibName: String(describing: MainViewController.self), bundle: Bundle.main) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public class Other : NSObject where C : MainViewControllerInterface, C : UIViewController, M : MainControllerToModelInterface, C.MODELVIEW == M { var c : C? override init() { let m = M() self.c = C(modelView: m) super.init() } } 

self.c = C(modelView: m)这一行给了我这个错误non-nominal type 'C' does not support explicit initialization

从这个其他堆栈溢出问题我看到旧版Xcode版本中的这个错误意味着

cannot invoke initializer for type '%type' with an argument list of type '...' expected an argument list of type '...'

但是在操场上方编译器缺少什么?

我在swift4 / xcode9上。

更新

按照建议Use C.init(modelView: m) rather than C(modelView: m) ,错误会发生变化:

No 'C.Type.init' candidates produce the expected contextual result type '_?'

比@ vini-app建议删除UIViewController以使其工作。 我仍然不明白为什么当UIViewController存在时编译器不满意。 知道C有那种有效的init方法还不够吗?

每当初始化generics参数而不是“真实”类型时,您只需要显式使用init

 self.c = C.init(modelView: m) 

使用C.init(modelView: m)而不是C(modelView: m) 。 那应该解决它。

请检查 :

在你的代码中你正在做这样的C : MainViewControllerInterface, C : UIViewController

它将C视为ViewController,然后在ViewController中没有init ,如init(modelView: M)这就是为什么它的抛出错误

 public class Other : NSObject where C : MainViewControllerInterface, M : MainControllerToModelInterface, C.MODELVIEW == M { var c : C? override init() { let m = M() self.c = C(modelView: m) super.init() } } 
Interesting Posts