swift3 - Assigning bool variable to another bool variable gives THREAD 1 BAD_EXC error swift 3 -


i first declare variable methodtype using code

 var methodtype: bool? = nil 

then go ahead , set variable using segmented control (also called methodtype) this.

else if indexpath.row == 1 {         cell.methodtype.ishidden = false         cell.methodtype.selectedsegmentindex = uisegmentedcontrolnosegment         switch cell.methodtype.selectedsegmentindex{         case 0: methodtype = true         case 1: methodtype = false         default:             break         } 

then go , set boolean coredata property = methodtype variable this.

 expense.cash = methodtype!  expense.credit = !methodtype! 

however, when run app, thread 1 exc bad error reason? doing wrong?

i first explain why error occurs , misunderstanding is.

in these lines:

cell.methodtype.selectedsegmentindex = uisegmentedcontrolnosegment switch cell.methodtype.selectedsegmentindex{ case 0: methodtype = true case 1: methodtype = false default:     break } 

you set cell.methodtype.selectedsegmentindex uisegmentedcontrolnosegment. think uisegmentedcontrolnosegment constant value of -1. therefore, when switch on it, goes default branch selected index neither 0 or 1.

so after running above lines methodtype not set , still nil.

then try force unwrap using !, of course results in crash.

you have misunderstood how "bind" selectedsegmentedindex variable methodtype. 1 way follows:

replace current switch statement call addtarget:

cell.methodtype.addtarget(self, action: #selector(methodtypechanged), for: .valuechanged) 

then add method called methodtypechanged class:

func methodtypechanged(_ sender: uisegmentedcontrol) {     switch sender.selectedsegmentindex{     case 0: methodtype = true     case 1: methodtype = false     default:         break     } } 

you should consider case of user not selecting anything. when setting core data property, should check whether methodtype nil:

if let methodtype = self.methodtype {     expense.cash = methodtype } else {     // user hasn't selected anything. show error message or use default value. } 

also, think should remove credit property. seems have opposite value of cash, it's not needed. can know value of credit accessing cash.


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -