Better way to change state when child state changes #1908
Replies: 1 comment
-
Hey @kakaopayios. The code you're showing should compile, but I guess that you're trying to scope onto the You can thus probably try to implement it as: private var _contentOne: ContentOne.State = .init()
private var _contentTwo: ContentTwo.State = .init()
var content: Content {
get {
switch child.currentSelection {
case .childSelection1:
return .contentOne(_contentOne)
case .childSelection2:
return .contentTwo(_contentTwo)
}
}
set {
switch newValue {
case let .contentOne(newContent):
self._contentOne = newContent
case let .contentTwo(newContent):
self._contentTwo = newContent
}
}
} This can seems a little odd to have both content type alive at the same time. If you want to avoid this configuration, you can use this alternative way: var _content: Content? // Or a non-optional placeholder.
var content: Content {
get {
switch child.currentSelection {
case .childSelection1:
if case .contentOne = _content {
return _content!
}
_content = .contentOne(.init())
return _content!
case .childSelection2:
if case .contentTwo = _content {
return _content!
}
_content = .contentTwo(.init())
return _content!
}
}
set {
_content = newValue
}
} Both styles behave differently when you switch the Alternatively, you can maybe also remodel your domain so the selected state lives in the selection enum Selection {
case childSelection1(ContentOne.State)
case childSelection2(ContentTwo.State)
} But this is maybe not possible given the way your model is organized. It also behaves like the second solution, which may be something you don't want. Writing this response reminds me a similar one that I wrote in these discussions a few months ago. I'll try to find it back. Please let me know if this doesn't help. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I want to change my enum state when child state changed.
I can accomplish it by receiving and processing a child's action.
But I'm wondering if there's a better way.
Is it possible to observe the child's status value and automatically change my status?
here is my sample code.
Beta Was this translation helpful? Give feedback.
All reactions