过滤Coredata类型的数组

时间:2017-12-12 09:25:42

标签: ios swift core-data

我的tableview单元格中有一个字符串。现在我想检查该字符串是否在特定的数组中。如果该数组有字符串,我想删除该数组中的字符串。这就是我为此所尝试的......

另外,favMessages是一个名为FavoritedMessages

的coredata对象数组
var textInCell = cell.historyTextLabel.text

for k in favMessages {
    if let thefavData = k.value(forKey: "favData") as? String {                  
        if sdf == thefavData {
             favMessages = favMessages.filter{$0 != textInCell} // HERE ERROR IS THROWN 'Binary operator '!=' cannot be applied to operands of type 'FavoritedMessages' and 'String?''
        }
    }
}

我如何解决它,我无法弄明白......

3 个答案:

答案 0 :(得分:1)

在以下代码中编写属性名称而不是StringValue。

favMessages = favMessages.filter{$0.StringValue != textInCell}

答案 1 :(得分:0)

你可以这样做,

favMessages = favMessages.filter({$0["Your key name of database"] as! String != "string to be compared"})

在你的情况下,

favMessages = favMessages.filter({$0["favData"] as! String != textInCell})

希望这有帮助

答案 2 :(得分:0)

你有一个包含字符串的数组:

var strings = ["a", "b", "c", "d"]

要删除的元素:

var firstElement = "a"
var secondElement = "e"

print("Before removing: ", strings)
//Before removing:  ["a", "b", "c", "d"]

[firstElement, secondElement].forEach {
    if let index = strings.index(of: $0) {
        strings.remove(at: index)
    }
}

结果:

print("After removing: ", strings)
After removing:  ["b", "c", "d"]