How to define a protocol to include a property with @Published property wrapper

后端 未结 6 556
情话喂你
情话喂你 2020-12-15 09:42

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 ne

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 10:21

    We've encountered this as well. As of Catalina beta7, there doesn't seem to be any workaround, so our solution is to add in a conformance via an extension like so:

    
    struct IntView : View {
        @Binding var intValue: Int
    
        var body: some View {
            Stepper("My Int!", value: $intValue)
        }
    }
    
    protocol IntBindingContainer {
        var intValue$: Binding { get }
    }
    
    extension IntView : IntBindingContainer {
        var intValue$: Binding { $intValue }
    }
    

    While this is a bit of extra ceremony, we can then add in functionality to all the IntBindingContainer implementations like so:

    extension IntBindingContainer {
        /// Reset the contained integer to zero
        func resetToZero() {
            intValue$.wrappedValue = 0
        }
    }
    
    

提交回复
热议问题