ios - If/Else based on existence of object in array? -
i want trigger else statement if there no object @ indexpath in array.
the array
let exercisesets = unsortedexercisesets.sorted { ($0.setposition < $1.setposition) }
then use let cellsset = exercisesets[indexpath.row]
there chance, when user adding new cell, wont have exerciseset @ indexpath populate (adding new set existing array of sets) , need run else statement set blank cell rather attempting populate , crashing app.
however if use if let error:
initializer conditional binding must have optional type, not 'userexerciseset'
here whole function context if needed:
func configure(_ cell: newexercisetableviewcell, @ indexpath: indexpath) { if self.userexercise != nil { print("restoring cells existing exercise") let unsortedexercisesets = self.userexercise?.exercisesets?.allobjects as! [userexerciseset] let exercisesets = unsortedexercisesets.sorted { ($0.setposition < $1.setposition) } if let cellsset = exercisesets[indexpath.row] { // causes creash when user adds new set existing exercise cant populate, needs else statement add fresh cell cell.setnumber.text = string(cellsset.setposition) cell.repspicker.selectrow(int(cellsset.setreps), incomponent: 0, animated: true) let localeidentifier = locale(identifier: userdefaults.standard.object(forkey: "locale") as! string) let setweight = cellsset.setweight as! measurement<unitmass> let formatter = massformatter() formatter.numberformatter.locale = localeidentifier formatter.numberformatter.maximumfractiondigits = 2 if localeidentifier.usesmetricsystem { let kgweight = setweight.converted(to: .kilograms) let finalkgweight = formatter.string(fromvalue: kgweight.value, unit: .kilogram) let numerickgresult = finalkgweight.trimmingcharacters(in: characterset(charactersin: "0123456789.").inverted) cell.userexerciseweight.text = numerickgresult } else { let lbsweight = setweight.converted(to: .pounds) let finallbweight = formatter.string(fromvalue: lbsweight.value, unit: .pound) let numericlbresult = finallbweight.trimmingcharacters(in: characterset(charactersin: "0123456789.").inverted) cell.userexerciseweight.text = numericlbresult } } else { cell.setnumber.text = string((indexpath.row) + 1) }
you crazy this:
if let cellset = (indexpath.row < exercisesets.count ? exercisesets[indexpath.row] : nil) { // }
but more straightforward do:
if indexpath.row < exercisesets.count { let cellset = exercisesets[indexpath.row] ... }
Comments
Post a Comment