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

雨燕双飞 提交于 2019-12-04 03:32:50

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