Luc*_*tti 26 generics xcode ios swift swift4
我试图理解我在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()
}
}
Run Code Online (Sandbox Code Playgroud)
这条线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方法还不够吗?
and*_*n22 41
只需init在初始化泛型参数而不是"真实"类型时,只需显式使用:
self.c = C.init(modelView: m)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12534 次 |
| 最近记录: |