简体   繁体   中英

MVVM-Coordinators with SwiftUI: Problem with 'View' generic protocol

I'm trying to update my MVVM-Coordinators pattern to use it with SwiftUI and Combine.

To preserve abstraction, I use a ScenesFactory that handle the creation of, well, my scenes like the following:

final class ScenesFactory {
    let viewModelsFactory = SceneViewModelsFactory()
}

extension ScenesFactory: SomeFlowScenesFactory {
    func makeSomeScene() -> Scene {
        let someSceneInput = SomeSceneInput()
        let someSceneViewModel = viewModelsFactory.makeSomeSceneViewModel(with: someSceneInput)
        let someSceneView = SomeSceneView()

        someSceneView.viewModel = someSceneViewModel

        return BaseScene(view: someSceneView, viewModel: someSceneViewModel)
    }
}

Here is the implementation of a my Scene protocol:

public protocol Scene {
    var view:       some View       { get }
    var viewModel:  ViewModelOutput { get }

    init(view: some View, viewModel: ViewModelOutput)
}

The goal here is to be able to use UIHostingController to present my someScene.view but the compiler throws an error at my Scene protocol:

在此处输入图像描述 I thought the point of the some keyword was precisely to use generic protocols as a return type.

What am I missing?

I thought the point of the some keyword was precisely to use generic protocols as a return type.

Yes, but it seems that it's doesn't work that way in a protocol declaration, not really sure why.

But there is a way to fix this, use an associatedtype that is constrained to View , and the compiler stop complaining.

public protocol Scene {
    associatedtype Content: View
    var view: Content { get }
}

struct V: Scene {
    var view: some View {
        EmptyView()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM