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

北城余情 提交于 2019-12-21 09:23:26

问题


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.


回答1:


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.

Ternary 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 ternary, the result of the ternary is instead assigned. In cases that can't be simplified further (see below), this is how ternarys should be used.

This new form should raise red flags though. Why have the ternary 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


来源:https://stackoverflow.com/questions/41524938/result-values-in-expression-have-mismatching-types-and-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!