-3

I want have bool variable - isChecked.

What i want is, to set opposite value to that variable like that:

(viewModel.arrValues[row] as! TestItem).isChecked = ((viewModel.arrValues[row] as? TestItem)?.isChecked)!

Logic is simple, ! mark suppose to present opposite value. But above code not work. Why?

2
  • 4
    The ! goes in front (!x rather than x!).
    – Thilo
    Aug 22, 2017 at 12:06
  • Define "does not work". And what happens if you put the ! in front of the value you want the opposite of? Aug 22, 2017 at 12:07

2 Answers 2

3

Because putting an exclamation mark after a variable marks force unwrapping. In general, putting the exclamation mark after an expression means forcing something (force casting with as! or force unwrapping for optionals, etc.).

You have to put it before the value to negate a boolean expression.

(viewModel.arrValues[row] as! TestItem).isChecked = !((viewModel.arrValues[row] as? TestItem)?.isChecked)

0
1

Try adding the after equal

(viewModel.arrValues[row] as! TestItem).isChecked = !((viewModel.arrValues[row] as? TestItem)?.isChecked)

Not the answer you're looking for? Browse other questions tagged or ask your own question.