【问题标题】:Remove an object from an array without knowing the object's index?在不知道对象索引的情况下从数组中删除对象?
【发布时间】:2015-01-06 23:23:14
【问题描述】:

我正在使用 switch 语句来 1) 切换复选标记和 2) 将谓词添加/删除到谓词数组。如果我知道它的名称,但不知道它在数组中的索引,有没有办法删除它?如果没有,解决方法是什么?这是我的代码的相关部分。

var colorPredicates: [NSPredicate?] = []

// Switch statement
        case blueCell:
            if (cell.accessoryType == .None) {
                colorPredicates.append(bluePredicate)
                cell.accessoryType = .Checkmark
                println(colorPredicates) // debug code to see what's in there
            } else {
                let deleteIndex = find(colorPredicates, bluePredicate) // error: NSPredicate doesn't conform to Equatable.
                muscleGroupPredicates.removeAtIndex(deleteIndex)
                cell.accessoryType = .None
                }
        default:
            println("default case")

【问题讨论】:

  • 找到对象,然后将其移除。如果要删除多个,请向后索引。不需要花哨的代码。
  • 怎么样?这是我的问题。
  • 你知道如何使用循环吗?还有if 声明?
  • 是的。我想我需要一行代码将其从索引中删除。我将向数组中添加几项内容(switch 语句将包含 20 个左右的 case),并且我知道数组中项的名称。我只是想弄清楚如何在不确定的索引处查找已知项目,如果在界面上切换复选标记,则将其删除。我在 else 语句中尝试了 'let deleteIndex = find(colorPredicates, bluePredicate)' 并在 'removeAtIndex: deleteIndex' 中使用,但它不起作用。

标签: arrays core-data ios8 xcode6 nspredicate


【解决方案1】:

缺少数组的 Swift 方法以及缺少 NSSet 概念让人有些沮丧。您是否考虑过投射到NSArray?

var colorPredicates = [NSPredicate]() as NSArray

和

colorPredicates.removeObject(bluePredicate)

另外,我认为您的数据源设计存在缺陷:您不应该检查单元格的accessoryType 来做其他事情。该信息应该在您的数据源中,而不是在一些任意的 UI 设计元素中。

【讨论】:

  • 有问题的视图是一个 UITableView,其静态单元格包含供用户检查的选项。 switch 语句更新 UI 以告诉用户他/她是否选择了谓词并将其从谓词数组中添加/删除。
  • 进一步挖掘,我发现您回复的另一篇文章一针见血:我正在尝试做什么。 stackoverflow.com/questions/18157088/ios-compound-predicates
【解决方案2】:

我遗漏了一个“!”,导致编译器错误。

我发现这篇文章很有帮助:Remove an element in an array without hard-coding the index? in Swift

// Switch statement
        case blueCell:
            if (cell.accessoryType == .None) {
                colorPredicates.append(bluePredicate)
                cell.accessoryType = .Checkmark
                println(colorPredicates) // debug code to see what's in there
            } else {
                let deleteIndex = find(colorPredicates, bluePredicate)
                colorPredicates.removeAtIndex(deleteIndex!)
                cell.accessoryType = .None
                }
        //more cases within switch statement

        default:
            println("default case")

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2013-07-27
    • 2021-06-28
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    相关资源
    最近更新 更多