Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary conditional not working in SwiftUI

Tags:

swift

swiftui

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)
    }
}

like image 968
Zorayr Avatar asked Nov 03 '25 00:11

Zorayr


2 Answers

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)
}
like image 62
Dávid Pásztor Avatar answered Nov 04 '25 15:11

Dávid Pásztor


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!)")
    }
}
like image 21
davidev Avatar answered Nov 04 '25 14:11

davidev