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

查看:84
本文介绍了如何使用@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天全站免登陆