简体   繁体   English

带有 SwiftUI 的 MVVM 协调器:“查看”通用协议有问题

[英]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.我正在尝试更新我的 MVVM-Coordinators 模式以将其与 SwiftUI 和组合一起使用。

To preserve abstraction, I use a ScenesFactory that handle the creation of, well, my scenes like the following:为了保持抽象,我使用ScenesFactory来处理我的场景的创建,如下所示:

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:这是我的Scene协议的实现:

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:这里的目标是能够使用UIHostingController来呈现我的someScene.view但编译器在我的Scene协议中抛出错误:

在此处输入图像描述 I thought the point of the some keyword was precisely to use generic protocols as a return type.我认为some关键字的重点正是使用泛型协议作为返回类型。

What am I missing?我错过了什么?

I thought the point of the some keyword was precisely to use generic protocols as a return type.我认为 some 关键字的重点正是使用泛型协议作为返回类型。

Yes, but it seems that it's doesn't work that way in a protocol declaration, not really sure why.是的,但它似乎在protocol声明中不起作用,不太确定为什么。

But there is a way to fix this, use an associatedtype that is constrained to View , and the compiler stop complaining.但是有一种方法可以解决这个问题,使用一个被限制为Viewassociatedtype类型,编译器就会停止抱怨。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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