SwiftUI - alternative to if let with a conditional closure
For such cases I prefer the following approach
struct PersonView: View {
@State private var age: Int? = 0
var body: some View {
VStack {
Text("Just a test")
AgeText
}
}
private var AgeText: some View {
if let age = self.age, age > 0 {
return Text("Display Age: \(age)")
} else {
return Text("Age must be greater than 0!")
}
}
}
You are trying to do two check on the value of age: first you are making sure it is not nil
and then checking that it is greater than 0.
You can use map to get rid of potential nil
and then a ternary operator to conditionally change the text displayed:
var body: some View {
VStack {
Text("Just a test")
age.map { Text( $0 > 0 ? "Display Age: \($0)" : "Age must be greater than 0!") }
}
}
Swift 5.3 (Xcode 12)
Now you can use conditional binding right in the view builder:
if let age = age {
if age > 0 {
Text("Display Age: \(age)")
} else {
Text("Age must be greater than 0!")
}
} else {
Text("Age not found")
}
Refactor (Workes in older Swifts too)
You can refactor your code to something more basic like using a function:
var body: some View {
VStack {
Text("Just a test")
Text(text(age: age)) // Using the function
}
}
func text(age: Int?) -> String { // Defining the function
guard let age = age else { return "Age not found" }
if age > 0 { return "Display Age: \(age)" }
else { return "Age must be greater than 0!" }
}
In general, use functions where you need to cleanup your code. I hope future versions of Swift will support this directly as we expect.