In SwiftUI, to modify a View based on a condition, we can use a ternary operator, hence allowing two cases. But what do I do if I want to evaluate multiple conditions, so that it's more like a switch (multiple cases) than an if/else (two cases)?
To demonstrate, a Text view can be modified by a @State var isLoggedIn: Bool like this, using a ternary operator:
Text(self.isLoggedIn ? "Welcome!" : "Please log in")
If I now want to add more cases, what I would do is use a function, but that makes the code a lot longer than the simple elegance of the ternary operator:
struct ContentView: View {
enum Status {
case loggedIn, loggedOut, expired
}
@State var userStatus: Status
func displayMessage(status: Status) -> some View {
switch(status) {
case .loggedIn:
return Text("Welcome!")
case .loggedOut:
return Text("Please log in")
case .expired:
return Text("Session expired")
}
}
var body: some View {
displayMessage(status: userStatus)
// more views
}
}
So does anyone have any suggestions on how I can simplify and shorten the second code?