What is the best way to refactor nested conditions like this below? Thanks in advance!
var body: some View {
VStack {
if let condition = condition {
if condition2 {
if condition 3 {
Text("some view")
} else {
Text("some view")
}
} else {
Text("some view")
}
}
}
}
CodePudding user response:
Perhaps a little clearer since it removes the nested levels but “best” is very subjective
if condition != nil {
switch (condition2, condition3) {
case (false, _):
//...
case (true, true):
//....
case (true, false):
//...
}
}
CodePudding user response:
It might take a little more work, but I'd separate out the issue of deciding which conditions have been met from the view itself.
You have three subviews, and only three subviews, which can be displayed. You could express that with an enum with an expressive name, for example:
struct ContentView: View {
enum FruitType {
case apple, banana, pear
}
And you could then extract your decision logic into a function that returns an enum value:
func whichFruitToDisplay(fruit: Fruit) -> FruitType {
if growsInBritain {
if isSpherical {
return .apple
} else {
return .pear
}
} else {
return .banana
}
}
In your view, you then switch on the result of that function:
var body: some View {
if let fruit = fruit {
switch(whichFruitToDisplay(fruit)) {
case .apple:
...
case .pear:
...
case .banana:
...
}
}
}
So at the view layer, you're being absolutely clear that there are three possible options, and you give each a meaningful name to represent the reason they're chosen. And the actual choice is outside the view, so could be moved into a view model, or some other object, if it needed to be.