Consider the following code:
class ViewModel: ObservableObject {
@Published private(set) var value = 0
}
let vm = ViewModel()| import SwiftUI | |
| struct ContentView: View { | |
| @State var isFavorite = false | |
| var body: some View { | |
| FavoriteComponent(id: 42, isFavorite: self.$isFavorite) | |
| } | |
| } |
| // This code has a bug. When you try to make a change to the selection | |
| // it will not persist. The `selection` binding is never written to | |
| // no matter what you do in the UI. | |
| import SwiftUI | |
| struct TestView: View { | |
| @State var selection: Int? | |
| var body: some View { |
When you concatenate two publishers, one of which is a merge, you will get a leak reported in Xcode’s memory graph debugger.
The publisher can be as simple as:
self.cancellable = Publishers.Concatenate(
prefix: Empty(completeImmediately: true),
The following code sample demonstrates a nested data structure in SwiftUI. You can add rows, drill down into those rows, and then add rows to that child node.
If you drill down 2 levels deep, then tapping “Add row” button no longer updates the UI. But, if you drill out and then drill back in you will see that the rows have appeared.
Paste the following code in a SwiftUI preview to demonstrate:
import SwiftUI
struct NestedState: Equatable, Identifiable {FB7673786
Paste the code below into a playground, and try incrementing and decrementing the stepper. The buttons will sporadically enable and disable.
This only happens with the Stepper.init(onIncrement:onDecrement:) initializer. It will work fine with a binding.
import SwiftUI
import PlaygroundSupportFB7671513
If you run the code below in a playground you will see that tapping the buttons doesn’t change the UI.
However, if you move the GeometryReader to the outside of ViewModelView it will begin working again.
import SwiftUI
import PlaygroundSupport| extension Publisher where Failure == Never { | |
| func promoteError<E>(_ errorType: E.Type = E.self) -> AnyPublisher<Output, E> { | |
| func never<A>(_ never: Never) -> A {} | |
| return self | |
| .mapError(never) | |
| .eraseToAnyPublisher() | |
| } | |
| } |