gpt4 book ai didi

ios - 如果/否则基于数组中对象的存在?

转载 作者:行者123 更新时间:2023-11-30 12:34:22 25 4
gpt4 key购买 nike

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

数组是

let exerciseSets = unsortedExerciseSets.sorted { ($0.setPosition < $1.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 { ($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)
}

最佳答案

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

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

但这样做会更简单:

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

关于ios - 如果/否则基于数组中对象的存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43070278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com