Result values in '? :' expression have mismatching types '()' and 'Bool'

12,108

Note, I don't know Swift, but this doesn't appear to be a Swift specific problem. I can't explain the exact error, but I can show you how to write it properly.

Conditional expressions are used almost exclusively when you need to assign something to a variable or return a value, and have exactly 2 options to choose from.

This is what you're trying to do, but you've written it in a convoluted way that's likely confusing the compiler.

In the expression:

numbers.count > 0 ? deleteAllNumbersButton.isEnabled = true
                  : deleteAllNumbersButton.isEnabled = false

Because the "then" and "else" expressions both contain assignments, they evaluate (I'm assuming) to a Unit (())/"void". I'm guessing this is why it's yelling at you. It never makes sense to use a ternary to return a Unit (Actually, as noted in the comments, operator precedence is the real reason for the error).

What you likely meant was:

deleteAllNumbersButton.isEnabled = numbers.count > 0 ? true : false

Notice how instead of assigning in the conditional expression, the result of the expression is instead assigned. In cases that can't be simplified further (see below), this is how conditional expressions should be used.

This new form should raise red flags though. Why have the conditional expression evaluate to true/false? That's almost always a code smell. It's redundant given the condition already evaluates to a Boolean value.

Just reduce it down to:

deleteAllNumbersButton.isEnabled = numbers.count > 0
Share:
12,108
TheoK
Author by

TheoK

Updated on June 05, 2022

Comments

  • TheoK
    TheoK almost 2 years

    I have an array of Doubles, and a button which when pressed empties the array. I want the button to be enabled only when the count of the array is greater than zero. The code is the following:

    var numbers: [Double] = [] //At some point I add some numbers here
    
    numbers.count > 0 ? deleteAllNumbersButton.isEnabled = true : deleteAllNumbersButton.isEnabled = false
    

    The compiler complains:

    Result values in '? :' expression have mismatching types '()' and 'Bool'

    When put in an if statement it works just fine though. I can't understand the issue here. Has anyone seen this before? I use XCode 8.2.1 and Swift 3.

  • Martin R
    Martin R over 7 years
    Operator precedence is the reason for the compiler error, it is nicely explained in the linked-to thread.