Description
I have a protocol containing an associated type that needs to be inferred later and it called UIViewRepresentable
Then another protocol to add extra:
protocol UIViewRepresentableHelper: UIViewRepresentable {
var configuration: (UIViewType) -> () { get set }
}
extension UIViewRepresentableHelper {
func makeUIView(context: UIViewRepresentableContext<Self>) -> UIViewType { UIViewType() }
func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<Self>) { configuration(uiView) }
}
So any types conforming to the second one should be able to implement the first and second protocols together.
struct LabelView: UIViewRepresentableHelper {
typealias UIViewType = UILabel // <- Commenting out this line confuses the Xcode about TheTypeThatShouldBeInferred
var configuration = { (view: UILabel) in }
}
struct ButtonView: UIViewRepresentableHelper {
typealias UIViewType = UIButton // <- Commenting out this line confuses the Xcode about TheTypeThatShouldBeInferred
var configuration = { (view: UIButton) in }
}
The Issue:
But as comments in the code are saying, seems like Swift can not infer UIViewType
from the context of the closure. Also, Xcode confuses about the context of the already written configuration
.
The Question:
What could be done to get rid of at least one of the type annotations, or one line of code, or anything else to make it more elegant and less coded?
One of the expectations:
I hoped atleast something like this would work:
struct TextFieldView: UIViewRepresentableHelper {
var configuration: (UITextField)->() = { _ in }
}