If / Else是否基于数组中对象的存在?

时间:2017-03-28 12:59:36

标签: ios swift if-statement tableviewcell

如果我在数组中寻找没有对象,我想触发一个else语句。

数组是

let exerciseSets = unsortedExerciseSets.sorted { ($0.setPosition < $1.setPosition) }

然后我使用let cellsSet = exerciseSets[indexPath.row]

当用户添加新单元时,有可能在indexPath上已经有一个exerciseSet来填充它(将一个新集添加到现有的数组),所以我需要运行一个else声明设置一个空白单元格,而不是尝试填充它并使我的应用程序崩溃。

但是,如果我使用if let然后我会收到此错误:

  

条件绑定的初始化程序必须具有Optional类型,而不是   'UserExerciseSet'

如果需要,这是上下文的整个功能:

    func configure(_ cell: NewExerciseTableViewCell, at indexPath: IndexPath) {
    if self.userExercise != nil {
        print("RESTORING CELLS FOR THE EXISTING EXERCISE")
        let unsortedExerciseSets = self.userExercise?.exercisesets?.allObjects as! [UserExerciseSet]
        let exerciseSets = unsortedExerciseSets.sorted { ($0.setPosition < $1.setPosition) }

        if let cellsSet = exerciseSets[indexPath.row] { // this causes a creash when user adds new set to existing exercise as it cant populate, needs an else statement to 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)
        }

3 个答案:

答案 0 :(得分:0)

好的,所以你的问题是你试图访问数组中可能存在或不存在的值。

如果您只是尝试访问基于indexPath的值,则可能会崩溃,因为indexPath可能会引用不存在的值。另一方面,数组不返回可选项,因此您也不能使用if let

我有点像使用可选项的想法,那么如果它存在,那么如何引入一个可以返回可选项的函数呢。

类似的东西:

func excerciseSet(for indexPath: IndexPath, in collection: [UserExcerciseSet]) -> UserExcerciseSet? {
    guard collection.count > indexPath.row else {
        return nil
    }
    return collection[indexPath.row]
}

然后你可以说:

if let cellsSet = exerciseSet[for: indexPath, in: excerciseSets] {  
    //It was there...showtime :)
} else {
    cell.setNumber.text = String((indexPath.row) + 1)
}

希望对你有所帮助。

答案 1 :(得分:0)

你可以这样做一些疯狂的事情:

if let cellSet = (indexPath.row < exerciseSets.count ? exerciseSets[indexPath.row] : nil) {
    //
}

但这样做会更直接:

if indexPath.row < exerciseSets.count {
    let cellSet = exerciseSets[indexPath.row]
    ...
}

答案 2 :(得分:0)

只需根据您的数组计算检查索引:

if indexPath.item < exerciseSets.count {

    // Cell exists
    let cellsSet = exerciseSets[indexPath.row]

} else {
    // cell doesn't exists. populate new one
}