Apoorv Mote Apoorv Mote - 1 month ago 7x
iOS Question

if else shorthand crashes on setting bool in swift

I literally have 4 line of code.

var bool = true

let textField1 = UITextField()

let textField2 = UITextField()

bool ? textField1.enabled = false : textField2.enabled = false

The above code fails with following error.

enter image description here

if I write the following way the code works

if bool {

textField1.enabled = false
else {

textfield2.enabled = false

If I write the following way then short hand of if else works

bool ? print("It's True") : print("It's False")

Why is my code failing?


The reason is that Swift is not expecting you to behave like this. Thus, it sees the second term in the ternary as textField2.enabled, which is a Bool. But the first term, textField1.enabled = false, is not a Bool; it is a Void.

(That is why your print example works; both terms are Voids.)

As i_am_jorf says, you can work around this by disambiguating with parentheses.

However, it would be better not to do this at all. Your code is not very Swifty. You should not be using the ternary operator for side effects in this way. You should be using it for the result of each of its terms. This is much cleaner and even shorter:

(bool ? textField1 : textField2).enabled = false