ios – Wrapping a UIKit view with initializer that may throw inside a SwiftUI display

0
105


I would wish to know if there’s a good present approach to wrap a UIKit inside SwiftUI when the initializer of the UIKit part can throw an error.

As a context, I am utilizing this article to create a generic wrapper like this:

struct Wrap<Wrapped: UIView>: UIViewRepresentable {
    typealias Updater = (Wrapped, Context) -> Void

    var makeView: () -> Wrapped
    var replace: (Wrapped, Context) -> Void

    init(_ makeView: @escaping @autoclosure () -> Wrapped,
         updater replace: @escaping Updater) {
        self.makeView = makeView
        self.replace = replace
    }

    func makeUIView(context: Context) -> Wrapped {
        makeView()
    }

    func updateUIView(_ view: Wrapped, context: Context) {
        replace(view, context)
    }
}

extension Wrap {
    init(_ makeView: @escaping @autoclosure () -> Wrapped,
         updater replace: @escaping (Wrapped) -> Void) {
        self.makeView = makeView
        self.replace = { view, _ in replace(view) }
    }

    init(_ makeView: @escaping @autoclosure () -> Wrapped) {
        self.makeView = makeView
        self.replace = { _, _ in }
    }
}

Now, the issue is that, if the UIKit class has an initializer that may throw an error, trying to make use of it in a SwiftUI display won’t compile:

remaining class MyView: UIView {

    init(textual content: String) throws {
        throw NSError(area: NSOSStatusErrorDomain, code: 20)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been carried out")
    }
}

Compile error on Xcode

So what can be one of the simplest ways to deal with this type of state of affairs in a “SwiftUI” means?