ebg
1
I'm unsure if the below code is a compiler bug or a limitation of Swift generics. I'm trying to instantiate a generic type which is constrained to be a protocol (which includes the init), which is constrained be a concrete UIView subclass.
Xcode autocomplete finds the protocol init method on ViewType, but then emits a compiler error (note I have also tried ViewType.init(model:)). Based on the constraints, it seems unambiguous to me that let view: UIView = ViewType(model: model) should succeed. Should I raise a bug for this?
protocol ListModel {
}
protocol ListView where Self: UIView {
init(model: ListModel)
}
class ListController<ViewType>: UIViewController where ViewType: ListView {
func update(listModels: [ListModel]) {
let views = listModels.map { (model: ListModel) -> UIView in
let view: UIView = ViewType(model: model) // error
return view
}
/** ... add UIViews as subviews */
}
}
Here's the console error:
error: non-nominal type 'ViewType' does not support explicit initialization
let view: UIView = ViewType(model: model)
^~~~~~~~~~~~~~~~~~~~~~
ebg
2
This got stuck behind the askimet filter for a while, if anyone has any recommendations on opening bug here let me know.
Nevin
3
It looks like Objective-C interop is relevant to the problem, because it compiles fine if we make everything in pure Swift:
class MyView {}
class MyController {}
protocol ListModel {}
protocol ListView where Self: MyView {
init(model: ListModel)
}
class ListController<ViewType: ListView> : MyController {
func update(listModels: [ListModel]) {
let views = listModels.map { (model: ListModel) -> MyView in
let view: MyView = ViewType(model: model)
return view
}
}
}
But if we make MyView inherit from NSObject, then we get the error “Non-nominal type 'ViewType' does not support explicit initialization”.
jrose
(Jordan Rose)
4
I agree that this looks sensible. Please file a bug!