【发布时间】:2017-09-27 23:22:19
【问题描述】:
我试图理解我在 swift 中使用泛型做错了什么。
我创建了这个示例游乐场
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()
}
}
self.c = C(modelView: m) 行给了我这个错误non-nominal type 'C' does not support explicit initialization
来自this other stack overflow的问题我看到旧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 方法还不够吗?
【问题讨论】:
标签: ios swift xcode generics swift4