Non-rated type X does not support explicit initialization

I am trying to understand what I am doing wrong with generics in quick.

I created this trial site

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<M> : 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<C, M> : 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() } } 

line self.c = C(modelView: m) gives me this error non-nominal type 'C' does not support explicit initialization

From this other question, I see that this error in older versions of Xcode means

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

But is there no compiler on the playground above?

I am on swift4 / xcode9.

Update

After executing the Use C.init(modelView: m) rather than C(modelView: m) error changes:

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

Than @ vini-app has suggested removing the UIViewController for it to work. I still don't understand why the compiler is not happy when there is a UIViewController. Is it not enough to know that C has this valid init method?

+5
source share
3 answers

You just need to explicitly use init whenever you initialize a generic parameter, rather than a "real" type:

 self.c = C.init(modelView: m) 
+11
source

Use C.init(modelView: m) , not C(modelView: m) . That should fix it.

+1
source

Please check:

In your code, you do this: C : MainViewControllerInterface, C : UIViewController .

It treats C as a ViewController, then there is no init in the ViewController, for example init(modelView: M) , so its throwing error

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

Source: https://habr.com/ru/post/1272177/


All Articles