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

If/Else based on existence of object in array?

如果我在数组中查找的 indexPath 中没有对象,我想触发 else 语句。

数组是

let exerciseSets = unsortedExerciseSets.sorted { ([=11=].setPosition < .setPosition) }

那我用let cellsSet = exerciseSets[indexPath.row]

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

但是如果我使用 if let 然后我得到这个错误:

Initializer for conditional binding must have Optional type, not '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 { ([=12=].setPosition < .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)
        }

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

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

我有点喜欢使用可选的想法,那么引入一个可以return可选的函数怎么样?

类似于:

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)
}

希望对你有所帮助。

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

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

但这样做会更直接:

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

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

if indexPath.item < exerciseSets.count {

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

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