How to Define a Protocol With @Published Property Wrapper Type
A simple and elegant workaround
This article is originally published at https://swiftsenpai.com on May 17, 2020.
The Combine framework was introduced in WWDC 2019 and it is mainly used alongside SwiftUI. However, this does not limit us to use the Combine framework on our UIKit apps.
In fact, the @Published
property wrapper introduced in Combine is the perfect fit for any UIKit apps with MVVM architecture. We can use @Published
to elegantly link up the view controller with its view model so that the view controller can be notified automatically by any changes made on the view model.
Everything works nicely until the day where I wanted to define a protocol for my view model in order to achieve polymorphism using protocol-oriented programming. The problem arises because the current Swift version (5.2) does not support property wrapper definition in a protocol.
How should we go about defining @Published
property wrapper type in a protocol? Read on to find out more.
The Problem
Let’s say we have a view controller and a view model with a @Published
variable called name
. Whenever name
is set or updated, the name
publisher will notify MyViewController
to print out a…