Anyone know if SwiftUI support ternary conditionals? I have a text view with conditional argument (Text(badgeCount == nil ? " " :"\(badgeCount!)")) that displays an empty view. Surprisingly, it works if I remove the @State attribute from the view.
import SwiftUI
struct RedBadgeView: View {
@State var badgeCount: Int?
init (_ badgeCount: Int? = nil) {
self.badgeCount = badgeCount
}
var body: some View {
// Something about this Syntax is throwing off SwiftUI.
Text(badgeCount == nil ? " " :"\(badgeCount!)")
}
}
struct RedBadgeView_Previews: PreviewProvider {
static var previews: some View {
RedBadgeView(1)
}
}
There's no need to use the ternary operator here at all. Moreover, doing a nil check and then force unwrapping in a ternary operator is a bad idea.
Instead, you should use optional chaining to access the description of badgeCount and provide the " " as a default value.
Text(badgeCount?.description ?? " ")
However, your problem of the view not updating is coming from the fact that you never initialise your State, you just assign a value to its wrapped value. To access the state, you need to use the _ prefix before the variable name.
init (_ badgeCount: Int? = nil) {
self._badgeCount = State(initialValue: badgeCount)
}
Sure ternary conditions work. However you initialization of the State is wrong. You are initializing a regular Int.
init (_ badgeCount: Int? = nil) {
self.badgeCount = badgeCount // >> If you initializing an Int
self._badgeCount = State(initialValue: badgeCount) // >> If you initializing a State variable
}
Hence, everything will work with State aswell:
struct ContentView: View {
@State var badgeCount: Int?
init (_ badgeCount: Int? = nil) {
self._badgeCount = State(initialValue: badgeCount)
}
var body: some View {
Text(badgeCount == nil ? " " :"\(badgeCount!)")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With