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

Time:02-23

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

CodePudding user response:

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()
}
  • Related