Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

ios - non-nominal type X does not support explicit initialization

I'm trying to understand what I'm doing wrong with generics in swift.

I created this sample playground

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()
    }
}

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

From this other stack overflow question I see that this error in older Xcode versions means

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

But in the playground above what is the compiler missing?

I'm on swift4/xcode9.

Update

After following the suggestion Use C.init(modelView: m) rather than C(modelView: m) the error changes in:

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

Than @vini-app suggested to remove the UIViewController to make it works. By I still don't understand why the compiler is not happy when UIViewController is there. Is it not enough to know that C has that valid init method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need to use init explicitly whenever you're initializing a generic parameter rather than a "real" type:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...