marika.daboja
marika.daboja

Reputation: 991

Swift code question - what this code actually do? (? : meaning in this code sample)

I have below code in my XCode project and I'm not sure how to read it apart from the fact it's a function which does not return and which seems to be calling other functions from the viewModel (correct me if I'm wrong). But what conditions are there? What does '?' and ':' do here?

@objc
    func topLeftButtonTapped() {
        isRootNavigationViewController
            ? viewModel?.close()
            : viewModel?.previous()
        viewModel?.didAppear()
    }

Upvotes: 0

Views: 50

Answers (1)

Sulthan
Sulthan

Reputation: 130082

This is Ternary Conditional Operator, also called ternary expression, usually used as:

let myValue = condition ? valueIfConditionTrue : valueIfConditionFalse

Here the ternary expression is abused. Normally, the same would be expressed using an if-else statement:

if isRootNavigationViewController {
   viewModel?.close()
} else {
   viewModel?.previous()
}

Upvotes: 2

Related Questions