如何定义协议以包含带有@Published 属性包装器的属性 [英] How to define a protocol to include a property with @Published property wrapper

查看:26
本文介绍了如何定义协议以包含带有@Published 属性包装器的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当按照当前的 SwiftUI 语法使用 @Published 属性包装器时,似乎很难定义一个包含带有 @Published 的属性的协议,或者我肯定需要帮助 :)

When using @Published property wrapper following current SwiftUI syntax, it seems very hard to define a protocol that includes a property with @Published, or I definitely need help :)

当我在 View 和它的 ViewModel 之间实现依赖注入时,我需要定义一个 ViewModelProtocol 以便注入模拟数据以轻松预览.

As I'm implementing dependency injection between a View and it's ViewModel, I need to define a ViewModelProtocol so to inject mock data to preview easily.

这是我第一次尝试的,

protocol PersonViewModelProtocol {
    @Published var person: Person
}

我收到在协议中声明的属性‘人’不能有包装器".

I get "Property 'person' declared inside a protocol cannot have a wrapper".

然后我尝试了这个,

protocol PersonViewModelProtocol {
    var $person: Published
}

显然没有用,因为 '$' 是保留的.

Obviously didn't work because '$' is reserved.

我希望有一种方法可以在 View 和它的 ViewModel 之间建立一个协议,并利用优雅的 @Published 语法.非常感谢.

I'm hoping a way to put a protocol between View and it's ViewModel and also leveraging the elegant @Published syntax. Thanks a lot.

推荐答案

您必须明确并描述所有综合属性:

You have to be explicit and describe all synthetized properties:

protocol WelcomeViewModel {
    var person: Person { get }
    var personPublished: Published<Person> { get }
    var personPublisher: Published<Person>.Publisher { get }
}

class ViewModel: ObservableObject {
    @Published var person: Person = Person()
    var personPublished: Published<Person> { _person }
    var personPublisher: Published<Person>.Publisher { $person }
}

这篇关于如何定义协议以包含带有@Published 属性包装器的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆